Document

Mongoose

Schema

Connection

Document

Model

Query

QueryCursor

Aggregate

AggregationCursor

Schematype

Virtualtype

Error

SchemaArray

DocumentArrayPath

SubdocumentPath


Document.prototype.$errors

Type:
  • «property»

Hash containing current validation $errors.


Document.prototype.$getAllSubdocs()

Get all subdocs (by bfs)


Document.prototype.$ignore()

Parameters
  • path «String» the path to ignore

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

Example:

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

Document.prototype.$isDefault()

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

Checks if a path is set to its default.

Example

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

Document.prototype.$isDeleted()

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

Getter/setter, determines whether the document was removed or not.

Example:

  1. const product = await product.remove();
  2. product.$isDeleted(); // true
  3. product.remove(); // no-op, doesn't send anything to the db
  4. product.$isDeleted(false);
  5. product.$isDeleted(); // false
  6. product.remove(); // will execute a remove against the db

Document.prototype.$isEmpty()

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:

  1. const schema = new Schema({ nested: { foo: String } });
  2. const Model = mongoose.model('Test', schema);
  3. const doc = new Model({});
  4. doc.$isEmpty('nested'); // true
  5. doc.nested.$isEmpty(); // true
  6. doc.nested.foo = 'bar';
  7. doc.$isEmpty('nested'); // false
  8. doc.nested.$isEmpty(); // false

Document.prototype.$isNew

Type:
  • «property»

Boolean flag specifying if the document is new.


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:

  1. schema.pre('save', function() {
  2. // Mongoose will set `isNew` to `false` if `save()` succeeds
  3. this.$locals.wasNew = this.isNew;
  4. });
  5. schema.post('save', function() {
  6. // Prints true if `isNew` was set before `save()`
  7. console.log(this.$locals.wasNew);
  8. });

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:

  1. const doc = new Model({ name: 'test' });
  2. doc.$op; // null
  3. const promise = doc.save();
  4. doc.$op; // 'save'
  5. await promise;
  6. doc.$op; // null

Document.prototype.$parent()

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


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:

  1. const session = MyModel.startSession();
  2. const doc = await MyModel.findOne().session(session);
  3. doc.$session() === session; // true
  4. doc.$session(null);
  5. 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|*» optionally specify a type for “on-the-fly” attributes

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

Alias for set(), used internally to avoid conflicts


Document.prototype.$where

Type:
  • «property»

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

Example:

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

Document.prototype.depopulate()

Parameters
  • path «String»
Returns:
  • «Document» this

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

Example:

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

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


Document.prototype.directModifiedPaths()

Returns:
  • «Array»

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

  1. const schema = new Schema({ foo: String, nested: { bar: String } });
  2. const Model = mongoose.model('Test', schema);
  3. await Model.create({ foo: 'original', nested: { bar: 'original' } });
  4. const doc = await Model.findOne();
  5. doc.nested.bar = 'modified';
  6. doc.directModifiedPaths(); // ['nested.bar']
  7. doc.modifiedPaths(); // ['nested', 'nested.bar']

Document.prototype.equals()

Parameters
  • doc «Document» a document to compare
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|*» 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 the value of a path.

Example

  1. // path
  2. doc.get('age') // 47
  3. // dynamic casting to a string
  4. 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:

  1. const userSchema = new Schema({
  2. name: String,
  3. age: Number,
  4. country: String
  5. });
  6. const User = mongoose.model('User', userSchema);
  7. const user = await User.create({
  8. name: 'Hafez',
  9. age: 25,
  10. country: 'Egypt'
  11. });
  12. // returns an empty object, no changes happened yet
  13. user.getChanges(); // { }
  14. user.country = undefined;
  15. user.age = 26;
  16. user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } }
  17. await user.save();
  18. 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»

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.

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

Document.prototype.init()

Parameters
  • doc «Object» document returned by mongo

Initializes the document without setters or marking anything 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()

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.

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

  • value «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.

  1. doc.invalidate('size', 'must be less than 20', 14);
  2. doc.validate(function (err) {
  3. console.log(err)
  4. // prints
  5. { message: 'Validation failed',
  6. name: 'ValidationError',
  7. errors:
  8. { size:
  9. { message: 'must be less than 20',
  10. name: 'ValidatorError',
  11. path: 'size',
  12. type: 'user defined',
  13. value: 14 } } }
  14. })

Document.prototype.isDirectModified()

Parameters
  • path «String|Array<String>»
Returns:
  • «Boolean»

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

Example

  1. doc.set('documents.0.title', 'changed');
  2. doc.isDirectModified('documents.0.title') // true
  3. 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

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

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
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

  1. doc.set('documents.0.title', 'changed');
  2. doc.isModified() // true
  3. doc.isModified('documents') // true
  4. doc.isModified('documents.0.title') // true
  5. doc.isModified('documents otherProp') // true
  6. doc.isDirectModified('documents') // false

Document.prototype.isNew

Type:
  • «property»

Boolean flag specifying if the document is new.


Document.prototype.isSelected()

Parameters
  • path «String|Array<String>»
Returns:
  • «Boolean»

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

Example

  1. const doc = await Thing.findOne().select('name');
  2. doc.isSelected('name') // true
  3. 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:

  1. doc.mixed.type = 'changed';
  2. doc.markModified('mixed.type');
  3. 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»

Returns the list of paths that have been modified.


Document.prototype.overwrite()

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

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()

If this document is a subdocument or populated document, returns the document’s parent. Returns undefined otherwise.


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.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.

  • [callback] «Function» Callback

Returns:
  • «Promise,null»

Populates paths on an existing document.

Example:

  1. await doc.populate([
  2. 'stories',
  3. { path: 'fans', sort: { name: -1 } }
  4. ]);
  5. doc.populated('stories'); // Array of ObjectIds
  6. doc.stories[0].title; // 'Casino Royale'
  7. doc.populated('fans'); // Array of ObjectIds
  8. await doc.populate('fans', '-email');
  9. doc.fans[0].email // not populated
  10. await doc.populate('author fans', '-email');
  11. doc.author.email // not populated
  12. doc.fans[0].email // not populated

Document.prototype.populated()

Parameters
  • path «String»
Returns:
  • «Array,ObjectId,Number,Buffer,String,undefined»

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

Example:

  1. Model.findOne().populate('author').exec(function (err, doc) {
  2. console.log(doc.author.name) // Dr.Seuss
  3. console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'
  4. })

If the path was not populated, returns undefined.


Document.prototype.replaceOne()

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

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

Valid options:


Document.prototype.save()

Parameters
Returns:
  • «Promise,undefined» Returns undefined if used with callback or a Promise otherwise.

Saves this document by inserting a new document into the database if document.isNew is true, or sends an updateOne operation only with the modifications to the database, it does not replace the whole document in the latter case.

Example:

  1. product.sold = Date.now();
  2. product = await product.save();

If save is successful, the returned promise will fulfill with the document saved.

Example:

  1. const newProduct = await product.save();
  2. newProduct === product; // true

Document.prototype.schema

Type:
  • «property»

The document’s schema.


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|*» optionally specify a type for “on-the-fly” attributes

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

Sets the value of a path, or many paths.

Example:

  1. // path, value
  2. doc.set(path, value)
  3. // object
  4. doc.set({
  5. path : value
  6. , path2 : {
  7. path : value
  8. }
  9. })
  10. // on-the-fly cast to number
  11. doc.set(path, value, Number)
  12. // on-the-fly cast to string
  13. doc.set(path, value, String)
  14. // changing strict mode behavior
  15. doc.set(path, value, { strict: false });

Document.prototype.toJSON()

Parameters
  • options «Object»
Returns:
  • «Object»

The return value of this method is used in calls to JSON.stringify(doc).

This method accepts the same options as Document#toObject. To apply the options to every document of your schema by default, set your schemas toJSON option to the same argument.

  1. schema.set('toJSON', { virtuals: true })

See schema options for details.


Document.prototype.toObject()

Parameters
  • [options] «Object»

  • [options.getters=false] «Boolean» if true, apply all getters, including virtuals

  • [options.virtuals=false] «Boolean» if true, apply virtuals, including aliases. Use { getters: true, virtuals: false } to just apply getters, not virtuals

  • [options.aliases=true] «Boolean» if options.virtuals = true, you can set options.aliases = false to skip applying aliases. This option is a no-op if options.virtuals = false.

  • [options.minimize=true] «Boolean» if true, omit any empty objects from the output

  • [options.transform=null] «Function|null» if set, mongoose will call this function to allow you to transform the returned object

  • [options.depopulate=false] «Boolean» if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths.

  • [options.versionKey=true] «Boolean» if false, exclude the version key (__v by default) from the output

  • [options.flattenMaps=false] «Boolean» if true, convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject().

  • [options.useProjection=false] «Boolean»

    • If true, omits fields that are excluded in this document’s projection. Unless you specified a projection, this will omit any field that has select: false in the schema.
Returns:
  • «Object» js object

Converts this document into a plain-old JavaScript object (POJO).

Buffers are converted to instances of mongodb.Binary for proper storage.

Options:

  • getters apply all getters (path and virtual getters), defaults to false
  • aliases apply all aliases if virtuals=true, defaults to true
  • virtuals apply virtual getters (can override getters option), defaults to false
  • minimize remove empty objects, defaults to true
  • transform a transform function to apply to the resulting document before returning
  • depopulate depopulate any populated paths, replacing them with their original refs, defaults to false
  • versionKey whether to include the version key, defaults to true
  • flattenMaps convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false
  • useProjection set to true to omit fields that are excluded in this document’s projection. Unless you specified a projection, this will omit any field that has select: false in the schema.

Getters/Virtuals

Example of only applying path getters

  1. doc.toObject({ getters: true, virtuals: false })

Example of only applying virtual getters

  1. doc.toObject({ virtuals: true })

Example of applying both path and virtual getters

  1. doc.toObject({ getters: true })

To apply these options to every document of your schema by default, set your schemas toObject option to the same argument.

  1. schema.set('toObject', { virtuals: true })

Transform

We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional transform function.

Transform functions receive three arguments

  1. function (doc, ret, options) {}
  • doc The mongoose document which is being converted
  • ret The plain object representation which has been converted
  • options The options in use (either schema options or the options passed inline)

Example

  1. // specify the transform schema option
  2. if (!schema.options.toObject) schema.options.toObject = {};
  3. schema.options.toObject.transform = function (doc, ret, options) {
  4. // remove the _id of every document before returning the result
  5. delete ret._id;
  6. return ret;
  7. }
  8. // without the transformation in the schema
  9. doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  10. // with the transformation
  11. doc.toObject(); // { name: 'Wreck-it Ralph' }

With transformations we can do a lot more than remove properties. We can even return completely new customized objects:

  1. if (!schema.options.toObject) schema.options.toObject = {};
  2. schema.options.toObject.transform = function (doc, ret, options) {
  3. return { movie: ret.name }
  4. }
  5. // without the transformation in the schema
  6. doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  7. // with the transformation
  8. doc.toObject(); // { movie: 'Wreck-it Ralph' }

Note: if a transform function returns undefined, the return value will be ignored.

Transformations may also be applied inline, overridding any transform set in the options:

  1. function xform (doc, ret, options) {
  2. return { inline: ret.name, custom: true }
  3. }
  4. // pass the transform as an inline option
  5. doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }

If you want to skip transformations, use transform: false:

  1. schema.options.toObject.hide = '_id';
  2. schema.options.toObject.transform = function (doc, ret, options) {
  3. if (options.hide) {
  4. options.hide.split(' ').forEach(function (prop) {
  5. delete ret[prop];
  6. });
  7. }
  8. return ret;
  9. }
  10. const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
  11. doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
  12. doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
  13. doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }

If you pass a transform in toObject() options, Mongoose will apply the transform to subdocuments in addition to the top-level document. Similarly, transform: false skips transforms for all subdocuments.

Note that this is behavior is different for transforms defined in the schema

if you define a transform in schema.options.toObject.transform, that transform will not apply to subdocuments.

  1. const memberSchema = new Schema({ name: String, email: String });
  2. const groupSchema = new Schema({ members: [memberSchema], name: String, email });
  3. const Group = mongoose.model('Group', groupSchema);
  4. const doc = new Group({
  5. name: 'Engineering',
  6. email: 'dev@mongoosejs.io',
  7. members: [{ name: 'Val', email: 'val@mongoosejs.io' }]
  8. });
  9. // Removes `email` from both top-level document **and** array elements
  10. // { name: 'Engineering', members: [{ name: 'Val' }] }
  11. doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } });

Transforms, like all of these options, are also available for toJSON. See this guide to JSON.stringify() to learn why toJSON() and toObject() are separate functions.

See schema options for some more details.

During save, no custom options are applied to the document before being sent to the database.


Document.prototype.toString()

Helper for console.log


Document.prototype.undefined

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.unmarkModified()

Parameters
  • path «String» the path to unmark modified

Clears the modified state on the specified path.

Example:

  1. doc.foo = 'bar';
  2. doc.unmarkModified('foo');
  3. doc.save(); // changes to foo will not be persisted

Document.prototype.update()

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

Sends an update command with this document _id as the query selector.

Example:

  1. weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);

Valid options:


Document.prototype.updateOne()

Parameters
  • doc «Object»
  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean() and the Mongoose lean tutorial.

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.

  • callback «Function»

Returns:
  • «Query»

Sends an updateOne command with this document _id as the query selector.

Example:

  1. weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);

Valid options:


Document.prototype.validate()

Parameters
  • [pathsToValidate] «Array|String» list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list.

  • [options] «Object» internal options

  • [options.validateModifiedOnly=false] «Boolean» if true mongoose validates only modified paths.

  • [options.pathsToSkip] «Array|string» list of paths to skip. If set, Mongoose will validate every modified path that is not in this list.

  • [callback] «Function» optional callback called after validation completes, passing an error if one occurred

Returns:
  • «Promise» Promise

Executes registered validation rules for this document.

Note:

This method is called pre save and if a validation rule is violated, save is aborted and the error is returned to your callback.

Example:

  1. doc.validate(function (err) {
  2. if (err) handleError(err);
  3. else // validation passed
  4. });

Document.prototype.validateSync()

Parameters
  • pathsToValidate «Array|string» only validate the given paths

  • [options] «Object» options for validation

  • [options.validateModifiedOnly=false] «Boolean» If true, Mongoose will only validate modified paths, as opposed to modified paths and required paths.

  • [options.pathsToSkip] «Array|string» list of paths to skip. If set, Mongoose will validate every modified path that is not in this list.

Returns:
  • «ValidationError,undefined» ValidationError if there are errors during validation, or undefined if there is no error.

Executes registered validation rules (skipping asynchronous validators) for this document.

Note:

This method is useful if you need synchronous validation.

Example:

  1. const err = doc.validateSync();
  2. if (err) {
  3. handleError(err);
  4. } else {
  5. // validation passed
  6. }