【发布时间】:2015-06-06 16:32:08
【问题描述】:
我在获取数据时遇到了一些问题。
我有猫鼬计划。
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);
和获取方法
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' });
}
});
};
当我在 getPost 方法中调用 post.getAuthor() 时,他正在工作并通过 Id 找到用户。但是var author = post.getAuthor(); 有undefined 的值。
【问题讨论】:
-
当然你会得到
undefined,因为你正在尝试同步分配异步getAuthor函数的值。
标签: javascript node.js mongodb express mongoose