Unable to access the variable field of MongoDB in JavaScript

I'm facing an issue while trying to loop through an array I retrieved from mongodb. It seems the array is treated as a single element, and here is the code snippet:

const project = await Project.findOne({
    embedId: inititalData.embedId
});
console.log(project.variables,typeof project.variables,project.variables[0], "project")

const variables = project.variables;
console.log('Variables array:', variables);

// Check type and individual elements
console.log('Type of variables:', typeof variables);
if (variables instanceof Array) {
  console.log('First variable:', variables[0]);
} else {
  console.error('Variables is not an array');
}

Recent output:

{
  nodes: [
    {
      id: 'start101',
      type: 'startNode',
      data: [Object],
      position: [Object],
      width: 80,
      height: 40,
      selected: false,
      positionAbsolute: [Object],
      dragging: false
    },
    {
      id: 'Group-XUPJ',
      type: 'chatbotCommand',
      position: [Object],
      data: [Object],
      width: 260,
      height: 190,
      selected: true,
      positionAbsolute: [Object],
      dragging: false
    },
    {
      id: 'Group-8q8Z',
      type: 'chatbotCommand',
      position: [Object],
      data: [Object],
      width: 260,
      height: 190,
      selected: false,
      positionAbsolute: [Object],
      dragging: false
    }
  ],
  variables: [ 'var1', 'var2', 'var3' ],
  _id: new ObjectId('66a1d83534c4d42a3d5ae07e'),
  userId: 'user_2imJECN4mQmEz6p00ZeM9VTZAVt',
  name: 'asdfsdf',
  edges: [
    {
      source: 'start101',
      sourceHandle: 'a',
      target: 'Group-8q8Z',
      targetHandle: 'b',
      type: 'smoothstep',
      animated: true,
      className: 'border-2 border-gray-300',
      id: 'reactflow__edge-start101a-Group-8q8Zb'
    },
    {
      source: 'Group-8q8Z',
      sourceHandle: 'a',
      target: 'Group-XUPJ',
      targetHandle: 'b',
      type: 'smoothstep',
      animated: true,
      className: 'border-2 border-gray-300',
      id: 'reactflow__edge-Group-8q8Za-Group-XUPJb'
    },
    {
      source: 'Group-XUPJ',
      sourceHandle: 'a',
      target: 'Group-8q8Z',
      targetHandle: 'b',
      type: 'smoothstep',
      animated: true,
      className: 'border-2 border-gray-300',
      id: 'reactflow__edge-Group-XUPJa-Group-8q8Zb'
    }
  ],
  aiPrompts: [],
  aiModel: 'GPT-3.5',
  isScriptTagAvailable: true,
  createdAt: 2024-07-25T04:44:37.511Z,
  updatedAt: 2024-07-25T17:45:25.080Z,
  __v: 0,
  embedId: 9584913626795330,
  scriptTag: '<script async data-id="9584913626795330" id="taskDeno-embed-script" type="text/javascript" src="https://task-deno.vercel.app/js/embed.js">\n' +
    '</script>'
} 

👇project.variables       👇typeof project.variables 👇 project.variables[0]
[ 'var1', 'var2', 'var3' ] object                     undefined                 project


Variables array: [ 'var1', 'var2', 'var3' ]
Type of variables: object
Variables is not an array

Attempted to loop through array using the following code:

var obj;
project.variables.forEach((var) => {
   obj[var]=""
}

Output received:

[['var1','var2','var3']]:""

Expected output:

{
   'var1':"",
   'var2':"",
   'var3':"",
}

Answer â„–1

Have you attempted to break down your data in this manner:

const { items } = data;

And then iterate through it like this:

items.forEach(item => {
console.log(item); 
});

Afterwards, you could execute the following code:

const { items } = data;
const obj = {};
items.forEach(item => {
obj[item] = '';
});
console.log(obj);

Result: { item1: '', item2: '', item3: '' }

Answer â„–2

After encountering an issue caused by mongoose wrapping the object before usage, I was able to resolve it by implementing the following solution:

const project = await Project.findOne({
    embedId: initData.embedId
}).lean();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on saving php variable content in HTML "id"

Three variables are used in PHP: message_id, message_title, and message_content. Their content is stored inside HTML 'id' for later use with jQuery. Example: Variables: $id_variable = $rows['id_mensagem']; $message_title_edit = $rows ...

disappearing the link in a window.open popup

I have a situation where I am opening a window with the code window.open("mytest.aspx");. The issue arises when the user closes that pop-up window - I need to have the link on the parent page hidden. In essence, how can I hide the anchor link on the parent ...

Is there a way to circumvent the mouse up event?

I want to create a feature where when a user clicks down, something specific occurs. The sequence of events includes: An action taking place (which is not the focus here). Triggering a mouse up event. Implemented with: angular, html, css. Excludes: jQue ...

Unable to populate required field in mongoose document

I've been struggling for days to populate the user document with values from the bio data schema. So far, I'm only able to retrieve user data and not a combination of both schemas. Here is the code I've been working on: These are the mode ...

The conditional rendering issue in Mui DataGrid's renderCell function is causing problems

My Mui DataGrid setup is simple, but I'm encountering an issue with the renderCell function not rendering elements conditionally. https://i.sstatic.net/MEBZx.png The default behavior should display an EditIcon button (the pencil). When clicked, it t ...

how can I include an AngularJS variable as a parameter in an onclick function?

I attempted to utilize an AngularJS variable as an argument value inside onclick() in order to invoke a JavaScript function. Can someone provide me with instructions on how to achieve this? Here is my code: <div onclick="deleteArrival({{filterList.id} ...

Developing a personalized loop in handlebars templates

Just starting out with NodeJS and ExpressJS. I'm looking to customize a for loop in order to iterate through data from NodeJS using an index, akin to a non-traditional for loop. Take a look at the code snippet below, extracted from NodeJS, where I re ...

Unlocking keys of JavaScript class prior to class initialization

My constructor was becoming too large and difficult to maintain, so I came up with a solution to start refactoring it. However, even this new approach seemed bulky and prone to errors. constructor(data: Partial<BusinessConfiguration>) { if(!d ...

Can 1[&array] effectively replace &array[sizeof(array)/sizeof(array[0)], or is it overly complicated?

In the C programming language, there is no elementsof keyword available for obtaining the element count of an array. As a workaround, developers often use sizeof(Array)/sizeof(Array[0]), but this method requires repeatedly referencing the array variable na ...

Managing reverted MySQL transactions in a Node.js environment

I've been struggling with an issue for a few days now and I'm really hoping that you could provide some assistance. The problem lies in a node.js API using sequelize to interact with a MySQL database. When certain API calls are made, the code i ...

Remove image files from a directory with jQuery without relying on PHP or AJAX

Did you know that JQuery code is capable of executing unlink operations like PHP without using AJAX or a PHP file? For instance, if you wish to delete or unlink the file "aaa.jpg" located in the folder www.myproject.com/images/, you can achieve this by s ...

Subtracting 25% from the width of the web browser

After spending some time trying to solve this issue by myself, I've decided to reach out for help here where I know I can get some great responses. I am looking to determine the dimensions of the browser window minus 25%. Specifically, I have a two-c ...

Encountering the error "TypeError: Unable to access property 'findAll' of undefined" when using Sequlize

Currently, I am in the process of developing a CRUD Application utilizing PostgreSQL, Sequelize, and Express. I have been referring to this specific tutorial as my guide. However, it appears that there might be an issue with either my model or database con ...

What is the best way to implement a series of delayed animations in jQuery that are connected

Imagine you have the following items: <div id="d1"><span>This is div1</span></div> <div id="d2"><span>This is div2</span></div> <div id="d3"><span>This is div3</sp ...

Exposure to vulnerabilities in react-scripts

While working on my ReactJS app, I encountered a challenge related to vulnerability and security issues. The use of react-scripts library has highlighted numerous vulnerabilities in the latest version. Is it possible for me to directly update the depende ...

In ReactJS, the behavior of event.currentTarget differs from that of Vanilla Javascript

Is there an equivalent of event.currentTarget in ReactJS? When using event.target on click, I am getting the childDiv instead of the desired parentDiv. For example, in Vanilla Javascript: document.getElementById("parentDiv").onclick = function() { ...

What is the best way to combine two objects in AngularJS?

https://i.sstatic.net/qr5Bb.png If you have two JSON objects that need to be merged while removing duplicate properties, what approach would you take? ...

Is it possible to initialize an array literal using variables in the C programming language?

I've been trying to figure out if it's possible to initialize an array literal with variables, but I haven't found a definitive answer. Just to give some context, my goal is to pass an array literal to a function. Here's the code snippe ...

ngOptions compare by actual value

My webserver (node.js) serves a JSON file with a list of languages in the format: { "en" : "English", "fr" : "French" } and a separate JSON settings dictionary like this: { "currentLanguage" : "en" }. The select statement is as follows: <select ng-opti ...

Discover the ID or HREF linked to the current date using moment.js

I'm looking to dynamically add an active class to the current day in my web application. An example of how it currently works is shown below: $( document ).ready(function() { $('a[href*="2208"]').addClass('active'); }); My goal ...