This question already has an answer here:
I am sure somebody has asked this question before, but I can't find an answer that helps me. I'm running a node app that queries a MongoDB database using the Mongoose package, and the model is called Quote
. Direct querying of the DB works fine (i.e. there is no connection problem), but putting a query inside a function, so it can be run elsewhere, is not working. The following function is supposed to grab one record from the database, and then return it.
var getQuote = function(id) {
Quote.find({ quote_id : id }, function(err, quote) {
if (err) {
return console.error(err);
}
else {
return quote;
}
});
}
The following prints out undefined
console.log(getQuote(10));
I know it has to do with the fact that the database hasn't returned the result of the query yet - it's running asynchronously. So, how do I get that result? A lot of answers say "just throw in a callback!!" OK, how do I throw in a callback? callback()
is not a defined function! (sarcasm) Thank you in advance for humoring my ignorance!
via Peter Martinson
No comments:
Post a Comment