Skip to content

Commit b955724

Browse files
authored
Merge pull request #14671 from Automattic/vkarpov15/gh-14670
docs(findoneandupdate): improve example that shows findOneAndUpdate() returning doc before updates were applied
2 parents 1733478 + c1edf24 commit b955724

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

docs/tutorials/findoneandupdate.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ function findOneAndUpdate(filter, update, options) {}
1919
```
2020

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

2325
```acquit
2426
[require:Tutorial.*findOneAndUpdate.*basic case]

test/docs/findoneandupdate.test.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,18 @@ describe('Tutorial: findOneAndUpdate()', function() {
4040
age: Number
4141
}));
4242

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

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

48-
// `doc` is the document _before_ `update` was applied
49-
let doc = await Character.findOneAndUpdate(filter, update);
50-
doc.name; // 'Jean-Luc Picard'
51-
doc.age; // undefined
50+
// The result of `findOneAndUpdate()` is the document _before_ `update` was applied
51+
doc = await Character.findOneAndUpdate(filter, update);
52+
doc; // { name: 'Jean-Luc Picard', _id: ObjectId('000000000000000000000000') }
5253
// acquit:ignore:start
54+
assert.equal(doc._id.toHexString(), _id.toHexString());
5355
assert.equal(doc.name, 'Jean-Luc Picard');
5456
assert.equal(doc.age, undefined);
5557
// acquit:ignore:end

0 commit comments

Comments
 (0)