0

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.

2 Answers 2

10

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

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

Use $push with the $each modifier to append multiple values to the array field.

The following example appends each element of [ 90, 92, 85 ] to the scores array for the document where the name field equals joe:

db.students.updateOne(
   { name: "joe" },
   { $push: { scores: { $each: [ 90, 92, 85 ] } } }
)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.