3
我有一些数据获取问题。Nodejs和Mongoose数据获取
我有猫鼬计划。
PostSchema.methods.getAuthor = function() {
this.model('User').findById(this.author).exec(function (err, author){
if (author) {
console.log(author.username);
return author.username;
};
});
};
mongoose.model('Post', PostSchema);
和getMethod
exports.getPost = function (req, res) {
return Post.findById(req.params.id, function (err, post) {
if (!post) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (!err) {
var author = post.getAuthor();
console.log('author is: ', author);
return res.send({ status: 'OK', post:post });
} else {
res.statusCode = 500;
return res.send({ error: 'Server error' });
}
});
};
当我打电话post.getAuthor()
内getPost
方法,他的工作,并通过ID已找到用户。但var author = post.getAuthor();
有undefined
值。
当然你'undefined'与您试图同步异步分配'getAuthor'函数的值。 – zaynetro