Mongoose pre findOneAndUpdate挂钩问题

Jus*_*808 12 mongoose

我正在尝试更新预挂钩上的计数.问题是,由于某些未知的原因,findOneAndUpdate钩子无法访问该文档,据我所知.

我想这样做:

source.pre('findOneAndUpdate', function (next) {
  console.log('------------->>>>>> findOneAndUpdate: ');
  this.objects = this.objects || [];
  this.people = this.people || [];
  this.events = this.events || [];

  this.objectCount = this.objects.length;
  this.peopleCount = this.people.length;
  this.eventCount = this.events.length;

  next();
});
Run Code Online (Sandbox Code Playgroud)

但由于某些原因this,钩子中不是文档,它的Query对象似乎没用.

我错过了什么?如何使用预挂钩更新findOneAndUpdate上的计数?

小智 14

你可以做那样的smthng - >

source.pre('findOneAndUpdate', function (next) {
    console.log('------------->>>>>> findOneAndUpdate: ');
    this._update.$set.objects = [];
    this._update.$set.people = [];
    this._update.$set.events =  [];
    next();
});
Run Code Online (Sandbox Code Playgroud)

注意_update.$ set因为在上下文中"this"将是一个查询.所以你可以轻松添加你想要的任何东西!


rob*_*lep 7

文件规定:

查询中间件与文档中间件的区别在于微妙但重要的方式:在文档中间件中,this指的是正在更新的文档.在查询中间件中,mongoose不一定具有对正在更新的文档的引用,因此this引用查询对象而不是正在更新的文档.

更新操作通常会更新仅存在于数据库中的文档(它告诉MongoDB服务器:"查找文档X并将属性X设置为值Z"),因此Mongoose无法使用完整文档,因此,您可以不更新计数(至少需要访问要确定其长度的数组).

另外:为什么*Count你的架构中还需要单独的属性?如果要查询匹配特定大小的数组,可以$size直接在数组上使用运算符.

如果确实需要计数属性,那么对于每次更新,您需要跟踪对每个阵列所做的更改次数(根据添加/删除的项目数)并使用$inc运算符调整计数.