Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(findoneandupdate): improve example that shows findOneAndUpdate() returning doc before updates were applied #14671

Merged
merged 1 commit into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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