简体   繁体   English

通过在body,mongoose / mongodb中提供文档来更新多个文档

[英]Update multiple documents by providing documents in body, mongoose/mongodb

I need to update several documents by providing them in the body. 我需要通过在正文中提供几个文档来更新它们。 I can't query them, they must be provided. 我无法查询它们,必须提供它们。

Example: 例:

 var persons = [
    {id: 1, name'Joe', active: false}, 
    {id:2, name:'Jane', active: false})
];

This data is provided in the body and I want to set the active property to false. 这个数据在正文中提供,我想将active属性设置为false。

exports.setActivePropertyOnPersons = function(input,callback){
  for(var i = 0;i<input.body.length;i++){
    mongoose.model('person').findOne({id:input.body[i].id}, function(err, person){
      person.active = false;
      person.save();
    })
  }
  callback.send(200)
};

This code feels no good. 这段代码感觉不错。 Is there any better query to do this? 有没有更好的查询来做到这一点? I don't find any in the docs. 我在文档中找不到任何内容。

Try using the update command along with the " $in " operator: 尝试使用update命令和“ $ in ”运算符:

var ids= [];
for (var i=0 i<input.body.length; ++i) {
    ids.push(input.body[i].id);
}

mongoose.model('person').update( {id : {"$in":ids}}, {active:false} , {multi: true} , function(err,docs) { ... });

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM