Mongoose findOneAndUpdate in complex scenario

Hi,
In some cases you might want to update a sub document in a document in mongoDB collection which should return the result with projection. in mongoose I tried same so I’m going to share what it will look if you want to such a case.

let’s take a look at below source and see how we can achieve this.

now lets assume that we have a document with ‘requestAgent’ field as an Array and each item has index  on  _logId field and you have more that 1000 subDocument inside that and you need to update one of them. there might be several approaches to doing this, one of them is using findOneAndUpdate function from mongoose.
how does it works, take a look at here, based on the documentation, first argument should be search criteria object and you need to tell mongoDB which part of information is required.
if we query for the document it will return whole document with all of it’s subDocument , therefore we can do update only on document itself and we can’t find which subDocument needs to be modified because it’s returning all documents.
so we need to query for specific part of data. like below:

in this query we are using $elemMatch to tell mongoDB return only those elements that matches our condition.
then we are providing our update query as second argument.

here we tried to increment some values in document itself and it’s returned child from query.
and then we are going to put projection condition,

in fields  property we are trying to get whole queried subDocument, so we have to set this projection requestAgent.$':1   and since it’s not supported to have $ notation properties with new : true , we have to make that false and it will prevent you to get updated document as result, unless you don’t want any subDocument information as result.

Leave A Comment?