Don't run validation on this path or persist changes to this path.
doc.foo = null;
doc.$ignore('foo');
doc.save(); // changes to foo will not be persisted and validators won't be run
Checks if a path is set to its default.
MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
var m = new MyModel();
m.$isDefault('name'); // true
Getter/setter, determines whether the document was removed or not.
product.remove(function (err, product) {
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
})
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.
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
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.
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);
});
Marks a path as valid, removing existing validation errors.
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.
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.
Alias for set()
, used internally to avoid conflicts
Takes a populated field and returns it to its unpopulated state.
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 populated, this is a no-op.
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.
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']
Returns true if the Document stores the same data as doc.
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()
.
Hash containing current validation errors.
Explicitly executes population and returns a promise. Useful for ES2015 integration.
var promise = doc.
populate('company').
populate({
path: 'notes',
match: /airline/,
select: 'text',
model: 'modelName'
options: opts
}).
execPopulate();
// summary
doc.execPopulate().then(resolve, reject);
Returns the value of a path.
// path
doc.get('age') // 47
// dynamic casting to a string
doc.get('age', String) // "47"
The string version of this documents _id.
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 });
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.
Helper for console.log
path
was invalid kind
property for the error 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 } } }
})
Returns true if path
was directly set and modified, else false.
doc.set('documents.0.title', 'changed');
doc.isDirectModified('documents.0.title') // true
doc.isDirectModified('documents') // false
Checks if path
was explicitly selected. If no projection, always returns true.
Thing.findOne().select('nested.name').exec(function (err, doc) {
doc.isDirectSelected('nested.name') // true
doc.isDirectSelected('nested.otherName') // false
doc.isDirectSelected('nested') // false
})
Checks if path
was initialized.
Returns true if this document was modified, else false.
If path
is given, checks if a path or any full path containing path
as part of its path chain has been modified.
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
Boolean flag specifying if the document is new.
Checks if path
was selected in the source query which initialized this document.
Thing.findOne().select('name').exec(function (err, doc) {
doc.isSelected('name') // true
doc.isSelected('age') // false
})
Marks the path as having pending changes to write to the db.
Very helpful when using Mixed types.
doc.mixed.type = 'changed';
doc.markModified('mixed.type');
doc.save() // changes to mixed.type are now persisted
doc.colors = { primary: 'blue' };
will not contain colors.primary
. If true, modifiedPaths()
will return an array that contains colors.primary
. Returns the list of paths that have been modified.
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
.
Populates document references, executing the callback
when complete. If you want to use promises instead, use this function with execPopulate()
doc
.populate('company')
.populate({
path: 'notes',
match: /airline/,
select: 'text',
model: 'modelName'
options: opts
}, function (err, user) {
assert(doc._id === user._id) // the document itself is passed
})
// summary
doc.populate(path) // not executed
doc.populate(options); // not executed
doc.populate(path, callback) // executed
doc.populate(options, callback); // executed
doc.populate(callback); // executed
doc.populate(options).execPopulate() // executed, returns promise
Population does not occur unless a callback
is passed or you explicitly call execPopulate()
. Passing the same path a second time will overwrite the previous path options. See Model.populate() for explaination of options.
Gets _id(s) used during population of the given path
.
Model.findOne().populate('author').exec(function (err, doc) {
console.log(doc.author.name) // Dr.Seuss
console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'
})
If the path was not populated, undefined is returned.
Sends a replaceOne command with this document _id
as the query selector.
Saves this document.
product.sold = Date.now();
product.save(function (err, product) {
if (err) ..
})
The callback will receive two parameters
err
if an error occurredproduct
which is the saved product
As an extra measure of flow control, save will return a Promise.
product.save().then(function(product) {
...
});
The documents schema.
Sets the value of a path, or many paths.
// 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 });
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 })
See schema options for details.
{ getters: true, virtuals: false }
to just apply getters, not virtuals options.virtuals = true
, you can set options.aliases = false
to skip applying aliases. This option is a no-op if options.virtuals = false
. __v
by default) from the output JSON.stringify()
the result of toObject()
. Converts this document into a plain javascript object, ready for storage in MongoDB.
Buffers are converted to instances of mongodb.Binary for proper storage.
getters
apply all getters (path and virtual getters), defaults to falsevirtuals
apply virtual getters (can override getters
option), defaults to falseminimize
remove empty objects (defaults to true)transform
a transform function to apply to the resulting document before returningdepopulate
depopulate any populated paths, replacing them with their original refs (defaults to false)versionKey
whether to include the version key (defaults to true)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 })
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)// 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 options:
function xform (doc, ret, options) {
return { inline: ret.name, custom: true }
}
// pass the transform as an inline option
doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }
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;
}
var 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.
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: '[email protected]', members: [{ name: 'Val', email: '[email protected]' }] }); // 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.
Helper for console.log
Clears the modified state on the specified path.
doc.foo = 'bar';
doc.unmarkModified('foo');
doc.save(); // changes to foo will not be persisted
Sends an update command with this document _id
as the query selector.
weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);
Sends an updateOne command with this document _id
as the query selector.
weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);
Executes registered validation rules for this document.
This method is called pre
save and if a validation rule is violated, save is aborted and the error is returned to your callback
.
doc.validate(function (err) {
if (err) handleError(err);
else // validation passed
});
Executes registered validation rules (skipping asynchronous validators) for this document.
This method is useful if you need synchronous validation.
var err = doc.validateSync();
if (err) {
handleError(err);
} else {
// validation passed
}
© 2010 LearnBoost
Licensed under the MIT License.
https://mongoosejs.com/docs/api/document.html