I'm writing an node.js API with Mongoose,
But for the purpose of a task, I want to get the object as a variable from my find,
so I have this :
exports.get_info = function(_id) {
Session.findById(_id, function(err, session) {
if (err)
res.send(err);
console.log (session); // the object is good
return session; // trying to return it
});
};
but When I call :
session_ = sessions.get_info(id);
here session_
is undefined ...
Any ideas ?
Mongoose model find
it's an sync function, you can't get result immediately. You should use callback or much better solution - promise (mongoose supports promises):
exports.get_info = function(_id) {
return Session.findById(_id);
};
get_info(/* object id */)
.then(session > console.log(session))
.catch(err => console.log(err));
the right way to do it is :
exports.get_info = function(_id,callback) {
Session.findById(_id, function(err, session) {
if (err)
res.send(err);
console.log (session); // the object is good
callback(null,session); // trying to return it
});
};
in this way, you can get the session like this :
sessions.get_info(id,function(err,session){
if(err) console.log(err);
console.log(session);
});
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.