如何使用 $push (Mongoose) 将多个对象推送到数组中

How to push multiple objects in array using $push (Mongoose)

将多个对象推入数组时遇到很多问题。

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

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

  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}}

它只是将星期二和星期三推到主要位置,而不是将它们放在时间表数组中。

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

  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 次,但我觉得有更有效的方法。

您可以 Append Multiple Values to an Array 通过使用 $push$each。 示例:

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