繁体   English   中英

在猫鼬的每个查找查询中添加(注入)条件

[英]add(inject) a condition in every find query in mongoose

我想给所有我的类似于查找的查询添加(注入)条件,所谓的类似于查找的查询是指在其中具有查找的查询,例如findfindOnefindOneAndUpdatefindByIdAndUpdate和...

例如,我的代码中包含以下查询:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM