[英]Nodejs and Mongoose data fetching
我有一些數據提取問題。
我有貓鼬計划。
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' });
}
});
};
當我在getPost
方法中調用post.getAuthor()
他正在工作並找到了User by Id。 但是var author = post.getAuthor();
有undefined
價值。
正如@zaynetro所說,你錯誤地調用了你的getAuthor
方法。 它是一個異步方法,所以你應該接受一個回調參數,或者你可以返回一個promise。
但是你要做的事情已經內置於mongoose,它的被稱為查詢群體。
http://mongoosejs.com/docs/populate.html
您可以配置一個Post.author引用屬性,您可以將mongoose解析為該文檔。
var postSchema = Schema({
author: {
type: Schema.Types.ObjectId,
ref: 'User'
}
});
mongoose.model('Post', postSchema);
var userSchma = Schema({
name: String
});
mongoose.model('User', userSchema);
然后,在您的路線中,您的查詢將如下所示:
Post
.findById(req.params.id)
.populate('author')
.exec(function(err, post) {
if (err) {
return res.status(500).send({
error: 'Server error'
});
}
// post.author contains the content of your author document
return res.send(post);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.