0

I got results from the database(Mongo) one function I save the dome variable of based on the result, but I can't use that variable in out side function. how can I access the variable?

currently, I got a result with in the function using the console.but I use the same variable in outside undefined, however, i use I faced same error undefined. without a time out function how can I complete this.

     var all_mail;
     mailModel.find({}, function (err, docs) {
              console.log(docs); //Got results this console
              all_mail = docs;
               
            });
     console.log(all_mail); //This is showing undefind

1 Answer 1

1

You'll want to look into how node.js handles asynchronous behaviors. In this case, your callback function only has access to docs while in scope.

You're correct in thinking that if you wait long enough, your variable will most likely be assigned. However, this really isn't the node way of doing things.

Most likely you should do whatever you want to do with docs within the function you pass to find().

 mailModel.find({}, function (err, docs) {
   doSomething(docs);
 });

This may drastically change the structure of your program. You may also want to look into using promises (http://mongoosejs.com/docs/promises.html) with Mongoose and then using async/await as long as your version of node supports it.

I believe using promises with await would look something like:

var docs = await mailModel.find({}).exec();
doSomething(docs);
Sign up to request clarification or add additional context in comments.

Comments

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.