[英]Using Mongoose populate on two levels
I'm making a movie website to develop my MEAN-stack skills. 我正在制作一个电影网站,以发展我的MEAN-stack技能。 At the moment I am trying to grab a movie document out of my database. 目前,我正尝试从数据库中获取电影文档。 This movie document has a property reviews which is an array of ObjectId's with a reference to the Review model. 该电影文档具有一个属性评论,该属性评论是ObjectId的数组,其中包含对Review模型的引用。 I populated these Object Idsand each Review document has the following structure: 我填充了这些对象ID,并且每个Review文档具有以下结构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
user: {type: Schema.Types.ObjectId, ref:'User'},
movie: {type: Schema.Types.ObjectId, ref:'Movie'},
date: {type: Date, default: Date.now},
content: String
}, { usePushEach: true });
module.exports = mongoose.model('Review', schema);
I already populated the reviews property of my movie object that I grabbed from the server, but I was wondering how I could also populate the user property of every review object that I got. 我已经填充了从服务器获取的电影对象的reviews属性,但是我想知道如何也可以填充我获得的每个评论对象的user属性。 So instead of seeing an objectId I would see the actual user object. 因此,我没有看到objectId,而是看到了实际的用户对象。
My route on the server side: I populated the reviews property, but I don't know how to populate the user property inside of these review objects 我在服务器端的路线:我填充了评论属性,但是我不知道如何在这些评论对象中填充user属性
router.get('/getmovie/:id', function(req, res, next) {
var id = req.params.id;
Movie.findById(id, function(err, movie){
if (err) {
res.status(500).json({
message: "An error occurred",
obj: err
})
}
Review.populate(movie, {path: 'reviews'}, function(err, movie){
if (err) {
res.status(500).json({
message: "An error occurred",
obj: err
})
}
res.status(200).json({
Message: "success",
obj: movie
});
})
})
});
I think you can simplify your code by using .populate() . 我认为您可以使用.populate()简化代码。
Movie.findById(id).populate({
path: 'reviews',
populate: {
path: 'user'
}
}).exec(function(err, movie){
if (err) {
// make sure you add return or else the code will continue
return res.status(500).json({
message: "An error occurred",
obj: err
})
}
res.status(200).json({
Message: "success",
obj: movie
});
});
Note, you can only do up to 2 levels. 请注意,您最多只能执行2个级别。 Otherwise, you'll need to use .aggregate()
which is more complicated. 否则,您将需要使用更复杂的.aggregate()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.