Document


Document.prototype.$assertPopulated()

Parameters:
  • path «String|Array[String]» path or array of paths to check. $assertPopulated throws if any of the given paths is not populated.

  • [values] «Object» optional values to $set(). Convenient if you want to manually populate a path and assert that the path was populated in 1 call.

Returns:
  • «Document» this

Throws an error if a given path is not populated

Example:

const doc = await Model.findOne().populate('author');

doc.$assertPopulated('author'); // does not throw
doc.$assertPopulated('other path'); // throws an error

// Manually populate and assert in one call. The following does
// `doc.$set({ likes })` before asserting.
doc.$assertPopulated('likes', { likes });

Document.prototype.$clearModifiedPaths()

Returns:
  • «Document» this

Clear the document's modified paths.

Example:

const doc = await TestModel.findOne();

doc.name = 'test';
doc.$isModified('name'); // true

doc.$clearModifiedPaths();
doc.name; // 'test', `$clearModifiedPaths()` does **not** modify the document's data, only change tracking

Document.prototype.$clone()

Returns:
  • «Document» a copy of this document

Returns a copy of this document with a deep clone of _doc and $__.


Document.prototype.$createModifiedPathsSnapshot()

Returns:
  • «ModifiedPathsSnapshot» a copy of this document's internal change tracking state

Creates a snapshot of this document's internal change tracking state. You can later reset this document's change tracking state using $restoreModifiedPathsSnapshot().

Example:

const doc = await TestModel.findOne();
const snapshot = doc.$createModifiedPathsSnapshot();

Document.prototype.$errors

Type:
  • «property»

Hash containing current validation $errors.


Document.prototype.$getAllSubdocs()

Parameters:
  • [options] «Object» options. Currently for internal use.

Returns:
  • «Array»

Get all subdocs (by bfs)


Document.prototype.$getPopulatedDocs()

Returns:
  • «Array[Document]» array of populated documents. Empty array if there are no populated documents associated with this document.

Gets all populated documents associated with this document.


Document.prototype.$ignore()

Parameters:
  • path «String» the path to ignore

Don't run validation on this path or persist changes to this path.

Example:

doc.foo = null;
doc.$ignore('foo');
doc.save(); // changes to foo will not be persisted and validators won't be run

Document.prototype.$inc()

Parameters:
  • path «String|Array» path or paths to update

  • val «Number» increment path by this value

Returns:
  • «Document» this

Increments the numeric value at path by the given val. When you call save() on this document, Mongoose will send a $inc as opposed to a $set.

Example:

const schema = new Schema({ counter: Number });
const Test = db.model('Test', schema);

const doc = await Test.create({ counter: 0 });
doc.$inc('counter', 2);
await doc.save(); // Sends a `{ $inc: { counter: 2 } }` to MongoDB
doc.counter; // 2

doc.counter += 2;
await doc.save(); // Sends a `{ $set: { counter: 2 } }` to MongoDB

Document.prototype.$init()

Alias for .init


Document.prototype.$isDefault()

Parameters:
  • [path] «String»
Returns:
  • «Boolean»

Checks if a path is set to its default.

Example:

MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
const m = new MyModel();
m.$isDefault('name'); // true

Document.prototype.$isDeleted()

Parameters:
  • [val] «Boolean» optional, overrides whether mongoose thinks the doc is deleted

Returns:
  • «Boolean,Document» whether mongoose thinks this doc is deleted.

Getter/setter, determines whether the document was deleted. The Model.prototype.deleteOne() method sets $isDeleted if the delete operation succeeded.

Example:

const product = await product.deleteOne();
product.$isDeleted(); // true
product.deleteOne(); // no-op, doesn't send anything to the db

product.$isDeleted(false);
product.$isDeleted(); // false
product.deleteOne(); // will execute a remove against the db

Document.prototype.$isEmpty()

Parameters:
  • [path] «String»
Returns:
  • «Boolean»

Returns true if the given path is nullish or only contains empty objects. Useful for determining whether this subdoc will get stripped out by the minimize option.

Example:

const schema = new Schema({ nested: { foo: String } });
const Model = mongoose.model('Test', schema);
const doc = new Model({});
doc.$isEmpty('nested'); // true
doc.nested.$isEmpty(); // true

doc.nested.foo = 'bar';
doc.$isEmpty('nested'); // false
doc.nested.$isEmpty(); // false

Document.prototype.$isModified()

Alias of .isModified


Document.prototype.$isNew

Type:
  • «property»

Boolean flag specifying if the document is new. If you create a document using new, this document will be considered "new". $isNew is how Mongoose determines whether save() should use insertOne() to create a new document or updateOne() to update an existing document.

Example:

const user = new User({ name: 'John Smith' });
user.$isNew; // true

await user.save(); // Sends an `insertOne` to MongoDB

On the other hand, if you load an existing document from the database using findOne() or another query operation, $isNew will be false.

Example:

const user = await User.findOne({ name: 'John Smith' });
user.$isNew; // false

Mongoose sets $isNew to false immediately after save() succeeds. That means Mongoose sets $isNew to false before post('save') hooks run. In post('save') hooks, $isNew will be false if save() succeeded.

Example:

userSchema.post('save', function() {
  this.$isNew; // false
});
await User.create({ name: 'John Smith' });

For subdocuments, $isNew is true if either the parent has $isNew set, or if you create a new subdocument.

Example:

// Assume `Group` has a document array `users`
const group = await Group.findOne();
group.users[0].$isNew; // false

group.users.push({ name: 'John Smith' });
group.users[1].$isNew; // true

Document.prototype.$locals

Type:
  • «property»

Empty object that you can use for storing properties on the document. This is handy for passing data to middleware without conflicting with Mongoose internals.

Example:

schema.pre('save', function() {
  // Mongoose will set `isNew` to `false` if `save()` succeeds
  this.$locals.wasNew = this.isNew;
});

schema.post('save', function() {
  // Prints true if `isNew` was set before `save()`
  console.log(this.$locals.wasNew);
});

Document.prototype.$markValid()

Parameters:
  • path «String» the field to mark as valid

Marks a path as valid, removing existing validation errors.


Document.prototype.$op

Type:
  • «property»

A string containing the current operation that Mongoose is executing on this document. May be null, 'save', 'validate', or 'remove'.

Example:

const doc = new Model({ name: 'test' });
doc.$op; // null

const promise = doc.save();
doc.$op; // 'save'

await promise;
doc.$op; // null

Document.prototype.$parent()

Returns:
  • «Document»

Alias for parent(). If this document is a subdocument or populated document, returns the document's parent. Returns undefined otherwise.


Document.prototype.$populated()

Alias of .populated.


Document.prototype.$restoreModifiedPathsSnapshot()

Parameters:
  • snapshot «ModifiedPathsSnapshot» of the document's internal change tracking state snapshot to restore

Returns:
  • «Document» this

Restore this document's change tracking state to the given snapshot. Note that $restoreModifiedPathsSnapshot() does not modify the document's properties, just resets the change tracking state.

This method is especially useful when writing custom transaction wrappers that need to restore change tracking when aborting a transaction.

Example:

const doc = await TestModel.findOne();
const snapshot = doc.$createModifiedPathsSnapshot();

doc.name = 'test';
doc.$restoreModifiedPathsSnapshot(snapshot);
doc.$isModified('name'); // false because `name` was not modified when snapshot was taken
doc.name; // 'test', `$restoreModifiedPathsSnapshot()` does **not** modify the document's data, only change tracking

Document.prototype.$session()

Parameters:
  • [session] «ClientSession» overwrite the current session

Returns:
  • «ClientSession»

Getter/setter around the session associated with this document. Used to automatically set session if you save() a doc that you got from a query with an associated session.

Example:

const session = MyModel.startSession();
const doc = await MyModel.findOne().session(session);
doc.$session() === session; // true
doc.$session(null);
doc.$session() === null; // true

If this is a top-level document, setting the session propagates to all child docs.


Document.prototype.$set()

Parameters:
  • path «String|Object» path or object of key/vals to set

  • val «Any» the value to set

  • [type] «Schema|String|Number|Buffer|[object Object]» optionally specify a type for "on-the-fly" attributes

  • [options] «Object» optionally specify options that modify the behavior of the set

    • [options.merge=false] «Boolean» if true, setting a nested path will merge existing values rather than overwrite the whole object. So doc.set('nested', { a: 1, b: 2 }) becomes doc.set('nested.a', 1); doc.set('nested.b', 2);

Returns:
  • «Document» this

Alias for set(), used internally to avoid conflicts


Document.prototype.$timestamps()

Parameters:
  • [value] «Boolean» overwrite the current session

Returns:
  • «Document,boolean,undefined,void» When used as a getter (no argument), a boolean will be returned indicating the timestamps option state or if unset "undefined" will be used, otherwise will return "this"

Getter/setter around whether this document will apply timestamps by default when using save() and bulkSave().

Example:

const TestModel = mongoose.model('Test', new Schema({ name: String }, { timestamps: true }));
const doc = new TestModel({ name: 'John Smith' });

doc.$timestamps(); // true

doc.$timestamps(false);
await doc.save(); // Does **not** apply timestamps

Document.prototype.$validate()

Alias of .validate


Document.prototype.$where

Type:
  • «property»

Set this property to add additional query filters when Mongoose saves this document and isNew is false.

Example:

// Make sure `save()` never updates a soft deleted document.
schema.pre('save', function() {
  this.$where = { isDeleted: false };
});

Document.prototype.depopulate()

Parameters:
  • [path] «String|Array[String]» Specific Path to depopulate. If unset, will depopulate all paths on the Document. Or multiple space-delimited paths.

Returns:
  • «Document» this
See:

Takes a populated field and returns it to its unpopulated state.

Example:

Model.findOne().populate('author').exec(function (err, doc) {
  console.log(doc.author.name); // Dr.Seuss
  console.log(doc.depopulate('author'));
  console.log(doc.author); // '5144cf8050f071d979c118a7'
})

If the path was not provided, then all populated fields are returned to their unpopulated state.


Document.prototype.directModifiedPaths()

Returns:
  • «Array[String]»

Returns the list of paths that have been directly modified. A direct modified path is a path that you explicitly set, whether via doc.foo = 'bar', Object.assign(doc, { foo: 'bar' }), or doc.set('foo', 'bar').

A path a may be in modifiedPaths() but not in directModifiedPaths() because a child of a was directly modified.

Example:

const schema = new Schema({ foo: String, nested: { bar: String } });
const Model = mongoose.model('Test', schema);
await Model.create({ foo: 'original', nested: { bar: 'original' } });

const doc = await Model.findOne();
doc.nested.bar = 'modified';
doc.directModifiedPaths(); // ['nested.bar']
doc.modifiedPaths(); // ['nested', 'nested.bar']

Document.prototype.equals()

Parameters:
  • [doc] «Document» a document to compare. If falsy, will always return "false".

Returns:
  • «Boolean»

Returns true if this document is equal to another document.

Documents are considered equal when they have matching _ids, unless neither document has an _id, in which case this function falls back to using deepEqual().


Document.prototype.errors

Type:
  • «property»

Hash containing current validation errors.


Document.prototype.get()

Parameters:
  • path «String»
  • [type] «Schema|String|Number|Buffer|[object Object]» optionally specify a type for on-the-fly attributes

  • [options] «Object»
    • [options.virtuals=false] «Boolean» Apply virtuals before getting this path

    • [options.getters=true] «Boolean» If false, skip applying getters and just get the raw value

Returns:
  • «Any»

Returns the value of a path.

Example:

// path
doc.get('age') // 47

// dynamic casting to a string
doc.get('age', String) // "47"

Document.prototype.getChanges()

Returns:
  • «Object»

Returns the changes that happened to the document in the format that will be sent to MongoDB.

Example:

const userSchema = new Schema({
  name: String,
  age: Number,
  country: String
});
const User = mongoose.model('User', userSchema);
const user = await User.create({
  name: 'Hafez',
  age: 25,
  country: 'Egypt'
});

// returns an empty object, no changes happened yet
user.getChanges(); // { }

user.country = undefined;
user.age = 26;

user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } }

await user.save();

user.getChanges(); // { }

Modifying the object that getChanges() returns does not affect the document's change tracking state. Even if you delete user.getChanges().$set, Mongoose will still send a $set to the server.


Document.prototype.id

Type:
  • «property»
See:

The string version of this documents _id.

Note:

This getter exists on all documents by default. The getter can be disabled by setting the id option of its Schema to false at construction time.

new Schema({ name: String }, { id: false });

Document.prototype.init()

Parameters:
  • doc «Object» raw document returned by mongo

  • [opts] «Object»
    • [opts.hydratedPopulatedDocs=false] «Boolean» If true, hydrate and mark as populated any paths that are populated in the raw document

  • [fn] «Function»

Hydrates this document with the data in doc. Does not run setters or mark any paths modified.

Called internally after a document is returned from MongoDB. Normally, you do not need to call this function on your own.

This function triggers init middleware. Note that init hooks are synchronous.


Document.prototype.inspect()

Returns:
  • «String»

Helper for console.log


Document.prototype.invalidate()

Parameters:
  • path «String» the field to invalidate. For array elements, use the array.i.field syntax, where i is the 0-based index in the array.

  • err «String|Error» the error which states the reason path was invalid

  • val «Object|String|Number|any» optional invalid value

  • [kind] «String» optional kind property for the error

Returns:
  • «ValidationError» the current ValidationError, with all currently invalidated paths

Marks a path as invalid, causing validation to fail.

The errorMsg argument will become the message of the ValidationError.

The value argument (if passed) will be available through the ValidationError.value property.

doc.invalidate('size', 'must be less than 20', 14);

doc.validate(function (err) {
  console.log(err)
  // prints
  { message: 'Validation failed',
    name: 'ValidationError',
    errors:
     { size:
        { message: 'must be less than 20',
          name: 'ValidatorError',
          path: 'size',
          type: 'user defined',
          value: 14 } } }
})

Document.prototype.isDirectModified()

Parameters:
  • [path] «String|Array[String]»
Returns:
  • «Boolean»

Returns true if path was directly set and modified, else false.

Example:

doc.set('documents.0.title', 'changed');
doc.isDirectModified('documents.0.title') // true
doc.isDirectModified('documents') // false

Document.prototype.isDirectSelected()

Parameters:
  • path «String»
Returns:
  • «Boolean»

Checks if path was explicitly selected. If no projection, always returns true.

Example:

Thing.findOne().select('nested.name').exec(function (err, doc) {
   doc.isDirectSelected('nested.name') // true
   doc.isDirectSelected('nested.otherName') // false
   doc.isDirectSelected('nested')  // false
})

Document.prototype.isInit()

Parameters:
  • [path] «String»
Returns:
  • «Boolean»

Checks if path is in the init state, that is, it was set by Document#init() and not modified since.


Document.prototype.isModified()

Parameters:
  • [path] «String» optional

  • [options] «Object»
    • [options.ignoreAtomics=false] «Boolean» If true, doesn't return true if path is underneath an array that was modified with atomic operations like push()

Returns:
  • «Boolean»

Returns true if any of the given paths is modified, else false. If no arguments, returns true if any path in this document is modified.

If path is given, checks if a path or any full path containing path as part of its path chain has been modified.

Example:

doc.set('documents.0.title', 'changed');
doc.isModified()                      // true
doc.isModified('documents')           // true
doc.isModified('documents.0.title')   // true
doc.isModified('documents otherProp') // true
doc.isDirectModified('documents')     // false

Document.prototype.isNew

Type:
  • «property»
See:

Legacy alias for $isNew.


Document.prototype.isSelected()

Parameters:
  • path «String|Array[String]»
Returns:
  • «Boolean»

Checks if path was selected in the source query which initialized this document.

Example:

const doc = await Thing.findOne().select('name');
doc.isSelected('name') // true
doc.isSelected('age')  // false

Document.prototype.markModified()

Parameters:
  • path «String» the path to mark modified

  • [scope] «Document» the scope to run validators with

Marks the path as having pending changes to write to the db.

Very helpful when using Mixed types.

Example:

doc.mixed.type = 'changed';
doc.markModified('mixed.type');
doc.save() // changes to mixed.type are now persisted

Document.prototype.modifiedPaths()

Parameters:
  • [options] «Object»
    • [options.includeChildren=false] «Boolean» if true, returns children of modified paths as well. For example, if false, the list of modified paths for doc.colors = { primary: 'blue' }; will not contain colors.primary. If true, modifiedPaths() will return an array that contains colors.primary.

Returns:
  • «Array[String]»

Returns the list of paths that have been modified.


Document.prototype.overwrite()

Parameters:
  • obj «Object» the object to overwrite this document with

Returns:
  • «Document» this

Overwrite all values in this document with the values of obj, except for immutable properties. Behaves similarly to set(), except for it unsets all properties that aren't in obj.


Document.prototype.parent()

Returns:
  • «Document»

If this document is a subdocument or populated document, returns the document's parent. Returns the original document if there is no parent.


Document.prototype.populate()

Parameters:
  • path «String|Object|Array» either the path to populate or an object specifying all parameters, or either an array of those

  • [select] «Object|String» Field selection for the population query

  • [model] «Model» The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's ref field.

  • [match] «Object» Conditions for the population query

  • [options] «Object» Options for the population query (sort, etc)

    • [options.path=null] «String» The path to populate.

    • [options.populate=null] «string|PopulateOptions» Recursively populate paths in the populated documents. See deep populate docs.

    • [options.retainNullValues=false] «boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make populate() retain null and undefined array entries.

    • [options.getters=false] «boolean» if true, Mongoose will call any getters defined on the localField. By default, Mongoose gets the raw value of localField. For example, you would need to set this option to true if you wanted to add a lowercase getter to your localField.

    • [options.clone=false] «boolean» When you do BlogPost.find().populate('author'), blog posts with the same author will share 1 copy of an author doc. Enable this option to make Mongoose clone populated docs before assigning them.

    • [options.match=null] «Object|Function» Add an additional filter to the populate query. Can be a filter object containing MongoDB query syntax, or a function that returns a filter object.

    • [options.transform=null] «Function» Function that Mongoose will call on every populated document that allows you to transform the populated document.

    • [options.options=null] «Object» Additional options like limit and lean.

    • [options.forceRepopulate=true] «Boolean» Set to false to prevent Mongoose from repopulating paths that are already populated

    • [options.ordered=false] «Boolean» Set to true to execute any populate queries one at a time, as opposed to in parallel. We recommend setting this option to true if using transactions, especially if also populating multiple paths or paths with multiple models. MongoDB server does not support multiple operations in parallel on a single transaction.

  • [callback] «Function» Callback

Returns:
  • «Promise,null» Returns a Promise if no callback is given.
See:

Populates paths on an existing document.

Example:

// Given a document, `populate()` lets you pull in referenced docs
await doc.populate([
  'stories',
  { path: 'fans', sort: { name: -1 } }
]);
doc.populated('stories'); // Array of ObjectIds
doc.stories[0].title; // 'Casino Royale'
doc.populated('fans'); // Array of ObjectIds

// If the referenced doc has been deleted, `populate()` will
// remove that entry from the array.
await Story.delete({ title: 'Casino Royale' });
await doc.populate('stories'); // Empty array

// You can also pass additional query options to `populate()`,
// like projections:
await doc.populate('fans', '-email');
doc.fans[0].email // undefined because of 2nd param `select`

Document.prototype.populated()

Parameters:
  • path «String»
  • [val] «Any»
  • [options] «Object»
Returns:
  • «Array,ObjectId,Number,Buffer,String,undefined,void»

Gets _id(s) used during population of the given path.

Example:

const doc = await Model.findOne().populate('author');

console.log(doc.author.name); // Dr.Seuss
console.log(doc.populated('author')); // '5144cf8050f071d979c118a7'

If the path was not populated, returns undefined.


Document.prototype.replaceOne()

Parameters:
  • doc «Object»
  • [options] «Object»
  • [callback] «Function»
Returns:
  • «Query»
See:

Sends a replaceOne command with this document _id as the query selector.

Valid options:


Document.prototype.save()

Parameters:
Returns:
  • «Promise»
See:

Saves this document by inserting a new document into the database if document.isNew is true, or sends an