实际上this.model 不适用于(pre save hook/middlewares)pre.('save' 但this.model 将适用于update、findOneAndUpdate 的pre hook ..等
对于pre.('save' 挂钩,您需要使用this.constructor 而不是this.model,例如:this.constructor.count 或this.constructor.findOne 等。
在我的示例中,假设为 Country
创建
Schema
所以你可以像下面这样使用:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var CountrySchema = new Schema({
name: String,
//....
});
CountrySchema.pre('save', function(next) {
var self = this;
self.constructor.count(function(err, data) {
if(err){
return next(err);
}
// if no error do something as you need and return callback next() without error
console.log('pre save count==', data);
return next();
});
});
CountrySchema.pre('update', function (next) {
var self = this;
self.model.count(function(err, data) {
if(err){
return next(err);
}
// if no error do something as you need and return callback next() without error
console.log('pre update count===', data);
return next();
});
});
module.exports = mongoose.model('Country', CountrySchema);
或
可以使用mongoose.models['modelName'] like:例如mongoose.models['Country'].count()
CountrySchema.pre('save', function(next) {
mongoose.models['Country'].count(function(err, data) {
if(err){
return next(err);
}
console.log('pre save count==', data);
return next();
});
});
CountrySchema.pre('update', function (next) {
mongoose.models['Country'].count(function(err, data) {
if(err){
return next(err);
}
console.log('pre update count===', data);
return next();
});
});
注意:为什么 this.model 不能在 save 的 pre hook 中工作?
Middleware(也称为 pre 和 post 钩子)是在异步函数执行期间传递控制权的函数。
在 Mongoose 中有两种类型的中间件:
- 文档中间件和
- 查询中间件
-
文档中间件支持函数。
init、validate、save、remove
-
查询中间件支持函数。
count, find, findOne, findOneAndRemove, findOneAndUpdate, insertMany,update
在 Mongoose 中 查询中间件 this.model 是由 Mongoose 生成/定义的模型实例。在这个中间件this 中返回所有由 mongoose 定义的实例变量。
在 Document 中间件 this 返回所有 fields 您不是由 mongoose 定义的,所以 this.model 不是您定义的属性。对于上面的例子,我有name 属性,所以你可以通过this.name 得到它,这将显示你的请求值。但是当使用this.contructor 时,您将返回由猫鼬定义的实例变量,如返回Model 实例变量。