[英]add(inject) a condition in every find query in mongoose
I want to add(inject) a condition to all of my find-like queries, by find-like queries I mean queries that have find in them, like find
, findOne
, findOneAndUpdate
, findByIdAndUpdate
and ... 我想给所有我的类似于查找的查询添加(注入)条件,所谓的类似于查找的查询是指在其中具有查找的查询,例如find
, findOne
, findOneAndUpdate
, findByIdAndUpdate
和...
for example, I have this query in my code: 例如,我的代码中包含以下查询:
model.findOne({a: 1})
but I want this query to run: 但我希望此查询运行:
model.findOne({a: 1, b: 2})
and my purpose is that {b:2}
be in every query so I don't want to be typing it in every single query. 我的目的是在每个查询中都使用{b:2}
,所以我不想在每个查询中都键入它。
I tried to use schema.pre('find', function(){})
hook but I failed. 我尝试使用schema.pre('find', function(){})
挂钩,但失败了。
I used the hook like this: 我像这样使用钩子:
schema.pre('find', async function f(){
const query = Object.assign({}, { b: 2}, this.getQuery())
this.setOptions(query)
console.log(this.getQuery())
})
but the console.log shows that the query has not changed. 但是console.log显示查询未更改。
findOne
example: findOne
示例:
AuthorSchema.pre('findOne', function(next) {
// Put your logic here for whatever you want to "decorate" ...
let conditions = this.getQuery() // get the current conditions
conditions._id = "5b80f96e9fceda195ba853af" // Change to whatever you want
this._conditions = conditions // Set the new conditions
next();
});
Would make this: 会这样:
var result = Author.findOne({_id: "5b7fa665844b5ebfad064b1c" })
.populate("books")
.exec()
Return actually the record with ObjectId of 5b80f96e9fceda195ba853af
实际返回带有5b80f96e9fceda195ba853af
ObjectId的5b80f96e9fceda195ba853af
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.