Mongoose获取多个集合中的文档

时间:2017-01-20 07:22:12

标签: node.js mongodb mongoose

我有一个名为Movie的模式和一个名为User的模式,用户的模式是这样的:

var userSchema = new mongoose.Schema({
    movies:[{type:mongoose.Schema.ObjectId, ref: 'Movie'}],
    password:{type:String, required:true},
    username:{type:String, unique:true, required:true},
    wishlist:[{type:mongoose.Schema.ObjectId, ref: 'Movie'}],
    seen:[{type:mongoose.Schema.ObjectId, ref: 'Movie'}],
    liked:[{type:mongoose.Schema.ObjectId, ref: 'Movie'}],
    disliked:[{type:mongoose.Schema.ObjectId, ref: 'Movie'}]
});

我想查询moviesliked中的电影或movies中的电影,而不是seen中的电影。现在我这样做是为了对 Node.js 中的所有数据进行多次for循环,但这似乎不对,所以我想知道有没有办法在mongoose中做到这一点?

2 个答案:

答案 0 :(得分:0)

尝试使用mongoose的populate函数。如果我正确理解了你的问题,那么试试这个解决方案:

var populateQuery = [{path: 'movies'}, {path: 'liked'}]
User.find({'_id': id}).populate(populateQuery).execPopulate()

您可以尝试使用查询来获得所需的结果。

Mongoose populate docs

答案 1 :(得分:0)

我最终使用了这样的查询运算符$and$in$nin

User.findById(id, function (err, user) {
    Movie.find({
        $and: [{
            '_id': {$in: user.movies},
            '_id': {$in: user.liked},
            '_id': {$nin: user.seen}
        }]
    })
        .limit(20)
        .populate(populateQuery)
        .exec(function (err, movies) {
            //movies is the movies that are both in movies and liked and are not in seen
            res.send(movies);
        });
});