How to find and update a subdocument with Mongoose?

Sometimes, we want to find and update a subdocument with Mongoose.

In this article, we’ll look at how to find and update a subdocument with Mongoose.

How to find and update a subdocument with Mongoose?

To find and update a subdocument with Mongoose, we call findOneAndUpdate with the $set operator.

For instance, we write

Folder.findOneAndUpdate({
    "_id": folderId,
    "permissions._id": permission._id
  }, {
    "$set": {
      "permissions.$": permission
    }
  },
  (err, doc) => {

  }
);

to call findOneAndUpdate with an object with the $set property.

We use it to set the permissions array to permission by setting $set to

{
  "permissions.$": permission
}

Conclusion

To find and update a subdocument with Mongoose, we call findOneAndUpdate with the $set operator.