【问题标题】:How to push multiple objects in array using $push (Mongoose)如何使用 $push (Mongoose) 在数组中推送多个对象
【发布时间】:2020-02-05 05:18:07
【问题描述】:

将多个对象推入数组时遇到很多麻烦。

我已经尝试了该代码的几种不同变体,我最终要么将对象直接推送到数据库,要么只推送数组的最后一个对象

这是我目前正在尝试的代码,它有效,但只推送最后一个对象(在本例中为星期三)。

  collection.findOneAndUpdate(
  { name: 'yyy' }, 
  { $push: { schedule: monday, schedule: tuesday, schedule: wednesday}},
 function (error, success) {
       if (error) {
           console.log("error");
           console.log(error);
       } else {
           console.log("success");
           console.log(success);
       }
});

我试过了

collection.findOneAndUpdate(
  { name: 'yyy' }, 
  { $push: { schedule: monday, tuesday, wednesday}}

它只是将星期二和星期三推到了 main 中,而不是将它们放在 schedule 数组中。

这是我用于日程安排的架构

  schedule: [
    {
        day: { type: String, default: ""},
        closed: { type: Boolean, default: false },
        start: { type: Number, default: 0},
        startap: { type: String, default: "AM"},
        end: { type: Number, default: 0},
        endap: { type: String, default: "PM"}
    }
  ]

我想推送到日程表数组的日期变量和示例

var monday = { 
            day:"Monday", 
            closed: false, 
            start:"700", 
            startap:"AM", 
            end:"1900", 
            endap:"PM"
};

显然我可以正常运行并更新代码 7 次,但我觉得有一种更有效的方法。

【问题讨论】:

    标签: arrays mongoose mongoose-schema


    【解决方案1】:

    您可以使用$push$eachAppend Multiple Values to an Array。 示例:

    collection.findOneAndUpdate(
      { name: 'yyy' }, 
      { $push: { schedule: {$each: [monday, tuesday, wednesday]}}}...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 2018-05-23
      • 2019-04-08
      • 2018-09-14
      • 2019-01-06
      • 2020-06-04
      相关资源
      最近更新 更多