2016-09-07 110 views
0

我有一个带有一些子文档的文档,其中每个子文档都有一个布尔字段。在所有mongodb子文档中切换布尔型字段

{ 
    title: String 
    children: [{ 
     exit: Boolean, 
     doc: String 
    }] 
} 

有没有一种简单的方法使一个DB调用切换为所有子文档的所有文件,所有的布尔?

据我所看到的,我可以做..

Model.find() 
.then(function(items) { 
    // manipulate item.children and toggle the exit field. 
    // and save them one by one 
}) 

但有一个更简单的方法?

回答

0

,如果你想更新一个文档内的多个阵列,它始终是更好地一次查询它,把它带到服务器,变异一切然后再保存它来代替单一的旧文件

Model.find() 
.then(function(items) { 
    // manipulate item.children and toggle the exit field. 
    var newChildren = items.childrens.map(x => x.exit = false) 

    //replace the old children 
    items.children = newChildren 

    items.save(); // no this is not saving one by one. this command save this item once, including all of it's children 
}) 
+0

确定那是什么我做到了。我想我必须这样做。 – user1017674

+0

伟大的直觉:) – vdj4y

+0

我真的在寻找一些方法来保存所有的父文件“原子” - 通过一个单一的mongodb调用。我想我不能。 – user1017674

相关问题