简体   繁体   中英

how can i make a assign mongoose result in global variable in node js?

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM