-2

I want to get the data from mongoose. Here is my code:

let data = [];
const getUserInfo = () => {
  UserInfo.find({}, function(err, docs){
      data = docs;
      console.log(data); //first log
  });
  console.log(data); //second log
};
getUserInfo(); 

The first log will print the right data, but the second log will return an empty set. Why does that happen?

Joe
  • 41,484
  • 20
  • 104
  • 125
Bill Kong
  • 1
  • 1
  • 3
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – sinanspd May 25 '22 at 02:11
  • I read this article, change the getUserInfo to an async function and add the await syntax in front of the UserInfo.find(), but Mongoose will send me an error: "MongooseError: Query was already executed: UserInfo.find({})". – Bill Kong May 25 '22 at 03:26
  • Also check this out: https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Christian Vincenzo Traina May 25 '22 at 08:07

1 Answers1

0

You try this. Which gives you a simple layer and bug free code.

let data = [];
const getUserInfo = async () => {
  data = await UserInfo.find();
  console.log("inside :", data);
  return; 
};
getUserInfo();

console.log("after :", data);
  • I had tried this, but mongoose sent this message to me "MongooseError: Query was already executed: UserInfo.find({})". – Bill Kong May 25 '22 at 05:57