我不知道如何保持简洁,所以... 我正在学习express&mongodb,但遇到了以下问题: 我为用户提供了一个具有以下模式的集合:
name:{
type: String
},email:{
type: String
},active:{
type: Boolean,default:false,select:false
}
现在,如果要将活动字段设置为true,我需要根据用户的电子邮件选择文档。像这样:
const Users = require(./models/users');
const user = await Users.findOne({
email:"example@domain.com"
}).select("+active");
问题在于,在我的架构中,我有一个查询中间件,以防止选择非活动用户。
mySchema.pre(/^find/,function(next) {
this.find({ active: true});
next();
});
我的问题:在某些特定情况下是否可以避免中间件调用?例如,如果我要选择不活跃的用户?还是可以通过我的控制器将特定参数发送到中间件?
注意:当我禁用中间件但我需要此中间件时,代码可以正常工作。
我在coderwall.com上找到了一个可以正常工作的解决方案,但是问题是它在我的收藏夹中保存了一个额外的字段,我不希望这个字段
const mySchema = new Schema({
...
hookEnabled: {
type: Boolean,default: true
}
});
然后在模型中
mySchema.pre('/^find/',function(next,done){
if(this.hookEnabled){
this.find({ active: true});
}
next();
});