【问题标题】:How to query and update all documents array如何查询和更新所有文档数组
【发布时间】:2014-09-07 21:59:28
【问题描述】:

我有一个关于猫鼬的问题:

我在“mongodb”中有一个“用户”集合,他们都有“朋友”数组,我需要将新数据推送到特定用户的“朋友”数组,有没有办法用一个查询?

这是架构:

var userSchema = mongoose.Schema({
    name : String,
    pictureUrl : String,
    devices : [String],
    friends : [String]
});
mongoose.model('user',userSchema);

我想做这样的事情

friends = [7823g87yh87y,ou327ujjghd9,py98hd98y23yh];
newUser["_id"] = ObjectId(236487g872he87y78);

user.update(
    {"_id": friends}, 
    {$push: {"friends": newUser["_id"]}},
    function (err, data) {
        if (err)
            console.log(err);
    });

【问题讨论】:

  • 您能否编辑您的问题以包含用户架构和一些示例数据?
  • 我想获取所有用户“朋友”文档,更新“朋友”数组并保存,感谢回复

标签: mongoose


【解决方案1】:

您可以使用$in_id 与一组值匹配,并使用{multi: true} 选项将更新应用于所有匹配的文档,而不仅仅是第一个:

user.update(
    {"_id": {$in: friends}}, 
    {$push: {"friends": newUser["_id"]}},
    {multi: true},
    function (err, data) {
        if (err)
            console.log(err);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 2015-06-22
    • 2020-12-11
    • 2014-06-28
    • 1970-01-01
    • 2019-11-18
    相关资源
    最近更新 更多