Est*_*ask 3 mongoose mongodb node.js
如何可以记录针对特定型号计数都被收购save和update猫鼬前钩/中间件?
考虑到这this是update挂钩查询,这很好用:
schema.pre('update', function (next) {
this.model.count().then...
});
Run Code Online (Sandbox Code Playgroud)
但是save挂钩了
schema.pre('save', function (next) {
this.count().then...
});
Run Code Online (Sandbox Code Playgroud)
结果是
this.count不是一个函数
当调试回调,this在save钩和this.model在update钩似乎是"模型"(的实例Model).他们之间有什么区别?
为什么模型实例在save钩子错过count方法?如何统一这两个回调来获取文档?
我宁愿坚持this而不是硬编码模型,因为这允许方便地使用ES6类进行模式继承.
Sha*_*Roy 10
实际上this.model不适用于(预先保存钩子/中间件)pre.('save'但是this.model可以用于预钩update,findOneAndUpdate等等
对于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);
Run Code Online (Sandbox Code Playgroud)
要么
可以使用mongoose.models['modelName']像: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();
});
});
Run Code Online (Sandbox Code Playgroud)
NB:为什么this.model不预先工作save?
中间件(也称为前后挂钩)是在执行异步功能期间传递控制的函数.
在Mongoose中有两种类型的中间件:
- 记录中间件和
- 查询中间件
文档中间件支持功能.
init,validate,save,remove
函数支持查询中间件.
count,find,findOne,findOneAndRemove,findOneAndUpdate,insertMany,update
在Mongoose Query中,中间件 this.model是由Mongoose生成/定义的模型的实例.在这个中间件中this返回由mongoose定义的所有实例变量.
在文档中间件中 this返回您不是由mongoose定义的所有字段,因此this.model不是您定义的属性.对于上面的例子我name有财产,所以你可以通过this.name它来显示你要求的价值.但是当使用时,this.contructor你将返回由mongoose定义的实例变量,如返回Model 实例变量.