node.jsmongodbmongoose

Mongoose - How to read findOneAndUpdate result when includeResultMetadata flag is set?


I am using mongoose findOneAndUpdate (reference) query function with includeResultMetadata and lean flags set. It responds with object of type ModifyResult (reference) which looks like:

{ lastErrorObject:
   { n: 1,
     updatedExisting: false,
     upserted: 5e6a9e5ec6e44398ae2ac16a },
  value:
   { _id: 5e6a9e5ec6e44398ae2ac16a,
     name: 'Will Riker',
     __v: 0,
     age: 29 },
  ok: 1 }

I am trying to parse the response and write below mentioned conditions:-

  1. No matching record found
  2. Matching record found but update failed
  3. Success and get updated record/document

I am not able to write these conditions as I did not find the documentation much useful on how to read the response returned by database. Looking for some explanation around the response object.


Solution

  • You need to check lastErrorObject.n, lastErrorObject.updatedExisting, and value to determine the outcome.

    1. No matching record found (No document was found and no upsert happened)
    if (!result.value && !result.lastErrorObject.upserted) {
       console.log("No matching record found.");
    }
    

    value is null, meaning no document was found. upserted is also undefined, meaning no new document was created.

    1. Matching record found but update failed. In most cases, if a document is found but not updated, it's likely because the update operation didn't modify any field.
    if (result.value && result.lastErrorObject.n === 1 && !result.lastErrorObject.updatedExisting) {
        console.log("Matching record found, but no update occurred.");
    }
    

    value is not null, meaning a document was found. lastErrorObject.n === 1, meaning a document matched. updatedExisting === false, meaning the update didn't change anything.

    1. Success - Document was updated
    if (result.value && result.lastErrorObject.n === 1 && result.lastErrorObject.updatedExisting) {
        console.log("Success! The document was updated:", result.value);
    }
    

    value is not null, meaning a document was found. updatedExisting === true, meaning an existing document was modified.