【问题标题】:Mongoose get documents that are in multiple collectionsMongoose 获取多个集合中的文档
【发布时间】:2017-06-05 02:46:34
【问题描述】:

我有一个叫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 循环,但这似乎是错误的,所以我想知道在猫鼬中有什么方法可以做到这一点吗?

【问题讨论】:

  • 您可以尝试将聚合与 $match 一起使用,并且要检查 $match 中的各种条件,您可以使用 $and 和 $or 运算符来检查各种条件。

标签: node.js mongodb mongoose


【解决方案1】:

尝试使用猫鼬的填充功能。如果我正确理解了您的问题,请尝试以下解决方案:

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

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

Mongoose populate docs

【讨论】:

  • 我想你误解了我的问题,我想得到既是电影又是喜欢的电影,所以find的查询是我要找的不是人口部分
  • 你试过我写的代码了吗?它不适合您的目的吗?
  • 我找到了解决方案,让我将其发布为答案,您会看到我在寻找什么
  • 感谢您的回答
  • 您现在可以查看答案
【解决方案2】:

我最终使用了查询运算符 $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);
        });
});

【讨论】:

    猜你喜欢
    • 2019-05-26
    • 2015-12-10
    • 2016-06-20
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    相关资源
    最近更新 更多