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:-
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.
You need to check lastErrorObject.n
, lastErrorObject.updatedExisting
, and value
to determine the outcome.
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.
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.
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.