[英]add(inject) a condition in every find query in mongoose
我想給所有我的類似於查找的查詢添加(注入)條件,所謂的類似於查找的查詢是指在其中具有查找的查詢,例如find
, findOne
, findOneAndUpdate
, findByIdAndUpdate
和...
例如,我的代碼中包含以下查詢:
model.findOne({a: 1})
但我希望此查詢運行:
model.findOne({a: 1, b: 2})
我的目的是在每個查詢中都使用{b:2}
,所以我不想在每個查詢中都鍵入它。
我嘗試使用schema.pre('find', function(){})
掛鈎,但失敗了。
我像這樣使用鈎子:
schema.pre('find', async function f(){
const query = Object.assign({}, { b: 2}, this.getQuery())
this.setOptions(query)
console.log(this.getQuery())
})
但是console.log顯示查詢未更改。
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();
});
會這樣:
var result = Author.findOne({_id: "5b7fa665844b5ebfad064b1c" })
.populate("books")
.exec()
實際返回帶有5b80f96e9fceda195ba853af
ObjectId的5b80f96e9fceda195ba853af
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.