简体   繁体   中英

Using Mongoose populate on two levels

I'm making a movie website to develop my MEAN-stack skills. 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. I populated these Object Idsand each Review document has the following structure:

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. So instead of seeing an objectId I would see the actual user object.

这就是我从服务器检索到的电影对象的结构的样子

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

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() .

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. Otherwise, you'll need to use .aggregate() which is more complicated.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM