Document
Document.prototype.$assertPopulated()
Document.prototype.$clearModifiedPaths()
Document.prototype.$clone()
Document.prototype.$createModifiedPathsSnapshot()
Document.prototype.$errors
Document.prototype.$getAllSubdocs()
Document.prototype.$getPopulatedDocs()
Document.prototype.$ignore()
Document.prototype.$inc()
Document.prototype.$init()
Document.prototype.$isDefault()
Document.prototype.$isDeleted()
Document.prototype.$isEmpty()
Document.prototype.$isModified()
Document.prototype.$isNew
Document.prototype.$locals
Document.prototype.$markValid()
Document.prototype.$op
Document.prototype.$parent()
Document.prototype.$populated()
Document.prototype.$restoreModifiedPathsSnapshot()
Document.prototype.$session()
Document.prototype.$set()
Document.prototype.$timestamps()
Document.prototype.$validate()
Document.prototype.$where
Document.prototype.depopulate()
Document.prototype.directModifiedPaths()
Document.prototype.equals()
Document.prototype.errors
Document.prototype.get()
Document.prototype.getChanges()
Document.prototype.id
Document.prototype.init()
Document.prototype.inspect()
Document.prototype.invalidate()
Document.prototype.isDirectModified()
Document.prototype.isDirectSelected()
Document.prototype.isInit()
Document.prototype.isModified()
Document.prototype.isNew
Document.prototype.isSelected()
Document.prototype.markModified()
Document.prototype.modifiedPaths()
Document.prototype.overwrite()
Document.prototype.parent()
Document.prototype.populate()
Document.prototype.populated()
Document.prototype.replaceOne()
Document.prototype.save()
Document.prototype.schema
Document.prototype.set()
Document.prototype.toJSON()
Document.prototype.toObject()
Document.prototype.toString()
Document.prototype.unmarkModified()
Document.prototype.updateOne()
Document.prototype.validate()
Document.prototype.validateSync()
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 updateval
«Number» incrementpath
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 removed or not.
Example:
const product = await product.remove();
product.$isDeleted(); // true
product.remove(); // no-op, doesn't send anything to the db
product.$isDeleted(false);
product.$isDeleted(); // false
product.remove(); // 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 setval
«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. Sodoc.set('nested', { a: 1, b: 2 })
becomesdoc.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 _id
s, 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 thearray.i.field
syntax, wherei
is the 0-based index in the array.err
«String|Error» the error which states the reasonpath
was invalidval
«Object|String|Number|any» optional invalid value[kind]
«String» optionalkind
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 likepush()
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 fordoc.colors = { primary: 'blue' };
will not containcolors.primary
. If true,modifiedPaths()
will return an array that containscolors.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'sref
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 makepopulate()
retainnull
andundefined
array entries.[options.getters=false]
«boolean» if true, Mongoose will call any getters defined on thelocalField
. By default, Mongoose gets the raw value oflocalField
. For example, you would need to set this option totrue
if you wanted to add alowercase
getter to yourlocalField
.[options.clone=false]
«boolean» When you doBlogPost.find().populate('author')
, blog posts with the same author will share 1 copy of anauthor
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 likelimit
andlean
.[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:
- same as in Model.replaceOne
Document.prototype.save()
Parameters:
[options]
«Object» options optional options[options.session=null]
«Session» the session associated with this save operation. If not specified, defaults to the document's associated session.[options.safe]
«Object» (DEPRECATED) overrides schema's safe option. Use thew
option instead.[options.validateBeforeSave]
«Boolean» set to false to save without validating.[options.validateModifiedOnly=false]
«Boolean» Iftrue
, Mongoose will only validate modified paths, as opposed to modified paths andrequired
paths.[options.w]
«Number|String» set the write concern. Overrides the schema-levelwriteConcern
option[options.j]
«Boolean» set to true for MongoDB to wait until thissave()
has been journaled before resolving the returned promise. Overrides the schema-levelwriteConcern
option[options.wtimeout]
«Number» sets a timeout for the write concern. Overrides the schema-levelwriteConcern
option.[options.checkKeys=true]
«Boolean» the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option tofalse
to skip that check. See restrictions on field names[options.timestamps=true]
«Boolean» iffalse
and timestamps are enabled, skip timestamps for thissave()
.
Returns:
- «Promise»
See:
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:
product.sold = Date.now();
product = await product.save();
If save is successful, the returned promise will fulfill with the document saved.
Example:
const newProduct = await product.save();
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 setval
«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
Returns:
- «Document» this
Sets the value of a path, or many paths.
Alias for .$set
.
Example:
// path, value
doc.set(path, value)
// object
doc.set({
path : value
, path2 : {
path : value
}
})
// on-the-fly cast to number
doc.set(path, value, Number)
// on-the-fly cast to string
doc.set(path, value, String)
// changing strict mode behavior
doc.set(path, value, { strict: false });
Document.prototype.toJSON()
Parameters:
options
«Object»[options.flattenMaps=true]
«Boolean» if true, convert Maps to POJOs. Useful if you want toJSON.stringify()
the result.[options.flattenObjectIds=false]
«Boolean» if true, convert any ObjectIds in the result to 24 character hex strings.
Returns:
- «Object»
See:
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.
schema.set('toJSON', { virtuals: true });
There is one difference between toJSON()
and toObject()
options.
When you call toJSON()
, the flattenMaps
option defaults to true
, because JSON.stringify()
doesn't convert maps to objects by default.
When you call toObject()
, the flattenMaps
option is false
by default.
See schema options for more information on setting toJSON
option defaults.
Document.prototype.toObject()
Parameters:
[options]
«Object»[options.getters=false]
«Boolean» if true, apply all getters, including virtuals[options.virtuals=false]
«Boolean|Object» if true, apply virtuals, including aliases. Use{ getters: true, virtuals: false }
to just apply getters, not virtuals. An object of the form{ pathsToSkip: ['someVirtual'] }
may also be used to omit specific virtuals.[options.aliases=true]
«Boolean» ifoptions.virtuals = true
, you can setoptions.aliases = false
to skip applying aliases. This option is a no-op ifoptions.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 toJSON.stringify()
the result oftoObject()
.[options.flattenObjectIds=false]
«Boolean» if true, convert any ObjectIds in the result to 24 character hex strings.[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.
- If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has
Returns:
- «Object» js object (not a POJO)
See:
Converts this document into a plain-old JavaScript object (POJO).
Buffers are converted to instances of mongodb.Binary for proper storage.
Getters/Virtuals
Example of only applying path getters
doc.toObject({ getters: true, virtuals: false })
Example of only applying virtual getters
doc.toObject({ virtuals: true })
Example of applying both path and virtual getters
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.
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
function (doc, ret, options) {}
doc
The mongoose document which is being convertedret
The plain object representation which has been convertedoptions
The options in use (either schema options or the options passed inline)
Example:
// specify the transform schema option
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
// remove the _id of every document before returning the result
delete ret._id;
return ret;
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
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:
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
return { movie: ret.name }
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
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 schema options.
Any transform function specified in toObject
options also propagates to any subdocuments.
function deleteId(doc, ret, options) {
delete ret._id;
return ret;
}
const schema = mongoose.Schema({ name: String, docArr: [{ name: String }] });
const TestModel = mongoose.model('Test', schema);
const doc = new TestModel({ name: 'test', docArr: [{ name: 'test' }] });
// pass the transform as an inline option. Deletes `_id` property
// from both the top-level document and the subdocument.
const obj = doc.toObject({ transform: deleteId });
obj._id; // undefined
obj.docArr[0]._id; // undefined
If you want to skip transformations, use transform: false
:
schema.options.toObject.hide = '_id';
schema.options.toObject.transform = function (doc, ret, options) {
if (options.hide) {
options.hide.split(' ').forEach(function (prop) {
delete ret[prop];
});
}
return ret;
}
const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
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 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.
const memberSchema = new Schema({ name: String, email: String });
const groupSchema = new Schema({ members: [memberSchema], name: String, email });
const Group = mongoose.model('Group', groupSchema);
const doc = new Group({
name: 'Engineering',
email: 'dev@mongoosejs.io',
members: [{ name: 'Val', email: 'val@mongoosejs.io' }]
});
// Removes `email` from both top-level document **and** array elements
// { name: 'Engineering', members: [{ name: 'Val' }] }
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()
Returns:
- «String»
Helper for console.log
Document.prototype.unmarkModified()
Parameters:
path
«String» the path to unmark modified
Clears the modified state on the specified path.
Example:
doc.foo = 'bar';
doc.unmarkModified('foo');
doc.save(); // changes to foo will not be persisted
Document.prototype.updateOne()
Parameters:
doc
«Object»[options]
«Object» optional seeQuery.prototype.setOptions()
[options.lean]
«Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. SeeQuery.lean()
and the Mongoose lean tutorial.[options.strict]
«Boolean|String» overwrites the schema's strict mode option[options.timestamps=null]
«Boolean» If set tofalse
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.
Returns:
- «Query»
See:
Sends an updateOne command with this document _id
as the query selector.
Example:
weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 });
Valid options:
- same as in Model.updateOne
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» iftrue
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.
Returns:
- «Promise» Returns a 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 thrown.
Example:
await doc.validate({ validateModifiedOnly: false, pathsToSkip: ['name', 'email']});
Document.prototype.validateSync()
Parameters:
[pathsToValidate]
«Array|string» only validate the given paths[options]
«Object» options for validation[options.validateModifiedOnly=false]
«Boolean» Iftrue
, Mongoose will only validate modified paths, as opposed to modified paths andrequired
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,void» ValidationError if there are errors during validation, or undefined if there is no error.