How do I query using Mongoose, but then take that document to do other things?
-
25-10-2019 - |
문제
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 :
제휴하지 않습니다 StackOverflow