Skip to content

Commit 843c24c

Browse files
committed
docs(document): add more info on $isNew
Fix #11990
1 parent 3445d24 commit 843c24c

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

lib/document.js

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,35 @@ Object.defineProperty(Document.prototype, '$locals', {
300300

301301

302302
/**
303-
* Boolean flag specifying if the document is new.
303+
* Boolean flag specifying if the document is new. If you create a document
304+
* using `new`, this document will be considered "new". `$isNew` is how
305+
* Mongoose determines whether `save()` should use `insertOne()` to create
306+
* a new document or `updateOne()` to update an existing document.
307+
*
308+
* #### Example:
309+
* const user = new User({ name: 'John Smith' });
310+
* user.$isNew; // true
311+
*
312+
* await user.save(); // Sends an `insertOne` to MongoDB
313+
*
314+
* On the other hand, if you load an existing document from the database
315+
* using `findOne()` or another [query operation](/docs/queries.html),
316+
* `$isNew` will be false.
317+
*
318+
* #### Example:
319+
* const user = await User.findOne({ name: 'John Smith' });
320+
* user.$isNew; // false
321+
*
322+
* For subdocuments, `$isNew` is true if either the parent has `$isNew` set,
323+
* or if you create a new subdocument.
324+
*
325+
* #### Example:
326+
* // Assume `Group` has a document array `users`
327+
* const group = await Group.findOne();
328+
* group.users[0].$isNew; // false
329+
*
330+
* group.users.push({ name: 'John Smith' });
331+
* group.users[1].$isNew; // true
304332
*
305333
* @api public
306334
* @property $isNew
@@ -311,7 +339,7 @@ Object.defineProperty(Document.prototype, '$locals', {
311339
Document.prototype.$isNew;
312340

313341
/**
314-
* Boolean flag specifying if the document is new.
342+
* Legacy alias for `$isNew`.
315343
*
316344
* @api public
317345
* @property isNew

0 commit comments

Comments
 (0)