Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Merge Arrays with FindAndUpdate

I want to append an array to an existing array in mongoose via Schema.findByIdAndUpdate(...). It should look something like this:

Schema.findByIdAndUpdate(id, { $merge: { existingArray: otherArray } }, (...))

Example

If I have a doc in the database that looks like this:

{
    ids: [1,2,3,4]
    ...
}

and I want to update this document to look like this:

{
    ids: [1,2,3,4,5,6,7,8]
    ...
}

with the help of this array:

[5,6,7,8]

Is there any suitable operator for my intent?

like image 578
Flo Avatar asked Sep 15 '18 14:09

Flo


1 Answers

You can use $push operator with $each modifier.

Something like this

db.collection.findOneAndUpdate(
  { "_id" : id },
  { "$push": { "ids": { "$each": [5,6,7,8] }}}
)
like image 99
Ashh Avatar answered Sep 22 '22 04:09

Ashh