【问题标题】:Mongodb: update elements of multiple arrays in same document at a time [duplicate]Mongodb:一次更新同一文档中多个数组的元素[重复]
【发布时间】:2016-11-18 05:49:05
【问题描述】:

我使用$push 来更新一个数组的元素。但是,当我尝试更新多个数组的元素时,使用逗号分隔值保持$push,如下所示,它显示错误。是怎么做到的?

var conditions = { some condition };
var update = { $push : {Feedback : { Feedbacks:req.body.Feedbacks}}, {Strength : { Strengths:req.body.Strengths}}};
var options = { multi : true};

Model.update(conditions, update, options, callback);

架构是:

Model : {

Field1 : {
    type:Number 
},

Field2: { 
     type : String
 },

Feedback : {
        type: Array,
        Default:[]
    },

    Strength : {
        type: Array,
        Default: [],
    }
};

注意:它适用于一个数组更新(如果我在推送后只保留反馈数组)但不适用于多个数组更新。多个数组怎么办?

【问题讨论】:

  • 谢谢@Janan。它现在正在工作。我以前用不正确的方式保存花括号。

标签: javascript arrays node.js mongodb mongoose


【解决方案1】:

Push to two separate arrays in one update call in mongodb

Model.update(
   conditions, 
   updates,
   options,
   callback
)

var updates = 
{
   $push : 
   {
      Feedback : { $each: req.body.Feedbacks },
      Strength : { $each: req.body.Strengths }
   }
}

【讨论】:

    【解决方案2】:
       { $push: { <field1>: <value1>,
                  <field2>: <value2> } }
    

          $push : 
           {
             Feedback : { $each: req.body.Feedbacks },
             Strength : { $each: req.body.Strengths } }
    

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 2020-12-10
      • 1970-01-01
      • 2019-02-09
      • 2016-11-25
      相关资源
      最近更新 更多