Skip to content

Commit

Permalink
Merge pull request #14671 from Automattic/vkarpov15/gh-14670
Browse files Browse the repository at this point in the history
docs(findoneandupdate): improve example that shows findOneAndUpdate() returning doc before updates were applied
  • Loading branch information
vkarpov15 authored Jun 18, 2024
2 parents 1733478 + c1edf24 commit b955724
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
2 changes: 2 additions & 0 deletions docs/tutorials/findoneandupdate.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ function findOneAndUpdate(filter, update, options) {}
```

By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied.
In the following example, `doc` initially only has `name` and `_id` properties.
`findOneAndUpdate()` adds an `age` property, but the result of `findOneAndUpdate()` does **not** have an `age` property.

```acquit
[require:Tutorial.*findOneAndUpdate.*basic case]
Expand Down
12 changes: 7 additions & 5 deletions test/docs/findoneandupdate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,18 @@ describe('Tutorial: findOneAndUpdate()', function() {
age: Number
}));

await Character.create({ name: 'Jean-Luc Picard' });
const _id = new mongoose.Types.ObjectId('0'.repeat(24));
let doc = await Character.create({ _id, name: 'Jean-Luc Picard' });
doc; // { name: 'Jean-Luc Picard', _id: ObjectId('000000000000000000000000') }

const filter = { name: 'Jean-Luc Picard' };
const update = { age: 59 };

// `doc` is the document _before_ `update` was applied
let doc = await Character.findOneAndUpdate(filter, update);
doc.name; // 'Jean-Luc Picard'
doc.age; // undefined
// The result of `findOneAndUpdate()` is the document _before_ `update` was applied
doc = await Character.findOneAndUpdate(filter, update);
doc; // { name: 'Jean-Luc Picard', _id: ObjectId('000000000000000000000000') }
// acquit:ignore:start
assert.equal(doc._id.toHexString(), _id.toHexString());
assert.equal(doc.name, 'Jean-Luc Picard');
assert.equal(doc.age, undefined);
// acquit:ignore:end
Expand Down

0 comments on commit b955724

Please sign in to comment.