【问题标题】:Having trouble getting $in operator to update all documents by array of _id [duplicate]无法让 $in 运算符按 _id 数组更新所有文档 [重复]
【发布时间】:2017-08-16 09:01:17
【问题描述】:

这是我的架构:

    var User = new Schema({
        name: {type: String, required: true},
        email: {
            address: String,
            confirmed: Boolean,
            confirm_code: String
        },
        saved_artists: [Schema.ObjectId],
        new_releases: [Schema.ObjectId],
        sync_queue: {
            id: Number,
            status: String
        }
    });

var Artist = new Schema({
    spotify_id: {type: String, required: true},
    name: {type: String, required: true},
    recent_release: {type: {
        id: String,
        title: String,
        release_date: String,
        images: []
    }, required: true},
    users_tracking: [Schema.ObjectId]
});

这是我的更新查询:

User.update({_id: {$in: artist.users_tracking}}, {$addToSet: {'new_releases': artist._id}}, function (err) {
        if (err) {
            // todo turn into debug report
            console.log(err);
        }
        User.find({}, function (err, users) {
            console.log(users);
        })
    })

当我运行单元测试时,$in 只选择数组的第一个 _id 并更新那个并忽略任何其他的。输入数组如下所示:

["5993864f44456a1b50378bc3","5993864f44456a1b50378bc4"]

如果我像下面这样迭代地运行更新查询,它会正确输出:

for (var i =0; i < artist.users_tracking.length; i++){
        User.update({'_id': artist.users_tracking[i]}, {$addToSet: {'new_releases': artist._id}}, function(err) {

        })
    }

【问题讨论】:

    标签: arrays mongodb mongoose


    【解决方案1】:

    User.update() 更改为User.updateMany() 提供了预期的查询输出。

    【讨论】:

      【解决方案2】:

      您也可以设置multi option to true

      User.update({
          _id: { $in: artist.users_tracking }
      }, { 
          $addToSet: { new_releases: artist._id }
      }, { 
          multi: true 
      }, ...)
      

      【讨论】:

        猜你喜欢
        • 2013-01-15
        • 2020-06-11
        • 2015-02-19
        • 2021-04-08
        • 2013-04-05
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多