Search code examples
arraysmongoosemongoose-schema

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


Having a lot of trouble pushing multiple objects into an array.

I've tried several different variations of this code, and I either end up pushing the objects directly to the db, or only pushing the last object of the array

Here is the code I'm trying currently, which works, but only pushes the last object (in this case wednesday).

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

I've tried

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

and it just pushed tuesday and wednesday to the main instead of placing them in the schedule array.

Here is the schema i'm using for 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"}
    }
  ]

Heres and example of the day variables i want to push to the schedule array

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

Obviously I could just run the fine and update code 7 times, but I feel like theres a more efficient way.


Solution

  • You can Append Multiple Values to an Array by using $push with $each. Example:

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