1

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);

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer, but when I try to use your code I get error "Unhandled error: TypeError: Cannot read property 'project' of undefined at myFunction"
Have you tried adding console.log(rez) before return rez in your own code? Does that work and print the correct result?
I tried that but it not work (not printing anything) and still the same error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.