Schema.prototype.pre()
Parameters
The «String|RegExp» method name or regular expression to match method name
[options] «Object»
[options.document] «Boolean» If
name
is a hook for both document and query middleware, set totrue
to run on document middleware. For example, setoptions.document
totrue
to apply this hook toDocument#deleteOne()
rather thanQuery#deleteOne()
.[options.query] «Boolean» If
name
is a hook for both document and query middleware, set totrue
to run on query middleware.callback «Function»
Defines a pre hook for the model.
Example
const toySchema = new Schema({ name: String, created: Date });
toySchema.pre('save', function(next) {
if (!this.created) this.created = new Date;
next();
});
toySchema.pre('validate', function(next) {
if (this.name !== 'Woody') this.name = 'Woody';
next();
});
// Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
toySchema.pre(/^find/, function(next) {
console.log(this.getFilter());
});
// Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
console.log(this.getFilter());
});
toySchema.pre('deleteOne', function() {
// Runs when you call `Toy.deleteOne()`
});
toySchema.pre('deleteOne', { document: true }, function() {
// Runs when you call `doc.deleteOne()`
});
当前内容版权归 mongoosejs 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 mongoosejs .