Skip to content

Commit

Permalink
Merge pull request #13474 from Automattic/vkarpov15/gh-13400
Browse files Browse the repository at this point in the history
docs(populate): add a little more info on why we recommend using ObjectId for `_id`
  • Loading branch information
vkarpov15 committed Jun 7, 2023
2 parents 5a2ca9f + 8aec9a6 commit 723f040
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions docs/populate.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@ what tells Mongoose which model to use during population, in our case
the `Story` model. All `_id`s we store here must be document `_id`s from
the `Story` model.

**Note**: `ObjectId`, `Number`, `String`, and `Buffer` are valid for use
as refs. However, you should use `ObjectId` unless you are an advanced
user and have a good reason for doing so.

<ul class="toc">
<li><a href="#saving-refs">Saving Refs</a></li>
<li><a href="#population">Population</a></li>
Expand Down Expand Up @@ -72,21 +68,22 @@ const author = new Person({
age: 50
});

author.save(function(err) {
if (err) return handleError(err);

const story1 = new Story({
title: 'Casino Royale',
author: author._id // assign the _id from the person
});
await author.save();

story1.save(function(err) {
if (err) return handleError(err);
// that's it!
});
const story1 = new Story({
title: 'Casino Royale',
author: author._id // assign the _id from the person
});

await author.save();
// that's it!
```

You can set the `ref` option on `ObjectId`, `Number`, `String`, and `Buffer` paths.
`populate()` works with ObjectIds, numbers, strings, and buffers.
However, we recommend using ObjectIds as `_id` properties (and thus ObjectIds for `ref` properties) unless you have a good reason not to.
That is because MongoDB will set `_id` to an ObjectId if you create a new document without an `_id` property, so if you make your `_id` property a Number, you need to be extra careful not to insert a document without a numeric `_id`.

<h2 id="population"><a href="#population">Population</a></h2>

So far we haven't done anything much different. We've merely created a
Expand Down

0 comments on commit 723f040

Please sign in to comment.