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

Pro*_*ket 0 arrays mongoose mongoose-schema

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

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

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

  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);
       }
});
Run Code Online (Sandbox Code Playgroud)

我试过了

collection.findOneAndUpdate(
  { name: 'yyy' }, 
  { $push: { schedule: monday, tuesday, wednesday}}
Run Code Online (Sandbox Code Playgroud)

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

这是我用于计划的架构

  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"}
    }
  ]
Run Code Online (Sandbox Code Playgroud)

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

var monday = { 
            day:"Monday", 
            closed: false, 
            start:"700", 
            startap:"AM", 
            end:"1900", 
            endap:"PM"
};
Run Code Online (Sandbox Code Playgroud)

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

Cuo*_*goc 5

您可以使用with将多个值附加到数组。例子:$push$each

collection.findOneAndUpdate(
  { name: 'yyy' }, 
  { $push: { schedule: {$each: [monday, tuesday, wednesday]}}}...
Run Code Online (Sandbox Code Playgroud)