Mongoose Merge Arrays with FindAndUpdate

Viewed 3894

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?

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] }}}
)
Related