tanja_a
tanja_a

Reputation: 11

how to store array from database in variable in javascript

I'm new to javascript and want to store (array) value from database in variable which I can manipulate later in my code. I'm using MongoDB and this is one example of the objects that are stored.

{
    "_id": {
        "$oid": "60a2247fcfe6fbbd6ce93ee0"
    },
    "project": ["4", "1"],
    "title": "Test",
    "url": "test",
    "urlTitle": "test1",
    "urlInstance": "https://www.google.com/",
    "__v": 0
}

I want to store the project values in an array (x). I use this code.. I figure out that myFunction() in not returning anything that's why in the console I get "x=undefined". what should I change in the code so the function return the value of the project? Thank you in advance.

function myFunction() {
  User.find({title: "Test"})
  .then(
    (myData) => {
    var rez=  myData[3].project;  
    return rez; 
  })

}

var x= new Array;
x= myFunction();
console.log ("x=" + x);

Upvotes: 1

Views: 383

Answers (1)

fravolt
fravolt

Reputation: 3001

I think this is related to database find operations being asynchronous, meaning they do not return immediately, but need some time to do so. Take a look at this documentation page for some more info.

Have you tried console.log-ing rez before returning it? You should see that it prints the result, but it happens after x=undefined is printed. In other words, myFunction is not waiting for the database retrieval to finish before returning.

Concretely, you'll want to await the result of your database retrieval.

async function myFunction() {
  // await here prevents the code from continuing before a result has been obtained
  let myData = await User.find({title: "Test"});

  let rez = myData[3].project;
  return rez;
}

async function retrieveData() {
  let x = await myFunction();
  console.log("x=" + x);
}

retrieveData();

Upvotes: 1

Related Questions