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:-
- No matching record found
- Matching record found but update failed
- 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.
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:-
- No matching record found
- Matching record found but update failed
- 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.
Share Improve this question asked Feb 17 at 15:18 rajan_saini.98rajan_saini.98 1507 bronze badges1 Answer
Reset to default 2You need to check lastErrorObject.n
, lastErrorObject.updatedExisting
, and value
to determine the outcome.
- 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.
- 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.
- 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.