数组中的Mongoose Update Array

时间:2015-07-03 06:18:52

标签: node.js mongodb mongoose

我有一个猫鼬模型如下:

{
    _id: ObjectId("557138249d46084df20620dd"),
    name: "Example"
    employee: [
        {
            username: "example@domain.com",
            address: [
                {
                    street: "123 Hill Ave"
                    country: US
                }
            ]
        }
    ]
}

可以有多个employee,每位员工都有{{1>} 地址。我想将数组内的员工的所有地址更新为空数组。所以,结果就像 -

array

如何查询将所有文档的地址更新为空数组?感谢。

2 个答案:

答案 0 :(得分:0)

好的,我得到了一个解决方案并且有效。感谢。

db.example.find().forEach(function(doc){
    doc.employee.forEach(function(em){
        em.address=[];
    })
    db.example.save(doc);
});

答案 1 :(得分:0)

单一的猫鼬方法无法做到这一点。它可以通过简单的循环完成并保存:

Model.findOne({query}, function(err, model) {
    if (err) {return callback(err);}

    for (var emp in model.employees) {
        model.employees[emp].address = [];
    }

    model.save(callback);
});