无法获取$ in运算符以按_id数组更新所有文档

时间:2017-08-15 23:49:06

标签: arrays mongodb mongoose

这是我的架构:

    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) {

        })
    }

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您也可以设置multi option to true

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