2015-07-03 66 views
0

猫鼬更新阵列我有如下猫鼬模型:内部阵列

{ 
    _id: ObjectId("557138249d46084df20620dd"), 
    name: "Example" 
    employee: [ 
     { 
      username: "[email protected]", 
      address: [ 
       { 
        street: "123 Hill Ave" 
        country: US 
       } 
      ] 
     } 
    ] 
} 

可以有很多employee和每个员工都有一个array地址。我想将阵列中的员工的所有地址更新为空数组。所以,结果会像 -

{ 
    _id: ObjectId("557138249d46084df20620dd"), 
    name: "Example" 
    employee: [ 
     { 
      username: "[email protected]", 
      address: [] 
     } 
    ] 
} 

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

+0

您还想更改您的预期输出中的键名,您将'employee'替换为'companies'? – Yogesh

回答

0

好的,我有一个解决方案,它的工作。谢谢。

db.example.find().forEach(function(doc){ 
    doc.employee.forEach(function(em){ 
     em.address=[]; 
    }) 
    db.example.save(doc); 
}); 
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); 
});