简体   繁体   中英

How do I query using Mongoose, but then take that document to do other things?

User.findOne({}, function(err, doc){
   //do stuff with "doc" here.
});

That's the way I currently do it. But what if I want to take "doc", and just do stuff.

User.findOne({}, function(err, doc){
   //do stuff with "doc" here.
});
runAnotherFunction(doc.name)
doc...

How do I take "doc" out of the "function" part?

Node is event driven, it's not procedural code like you're probably used to. Before mongoose can finish retrieving a record execution can already be well passed the call the findOne. Anything that needs to be done with the doc should happen in the callback (The "function" part).

you can try "step", https://github.com/creationix/step

This makes it easier to control logic flow.

See this for example:

async nodejs querying and processing results

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