猫鼬pre findOneAndUpdate挂钩问题 [英] Mongoose pre findOneAndUpdate hook issues

查看:75
本文介绍了猫鼬pre findOneAndUpdate挂钩问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to update counts on a pre hook. The issue is that for some unknown reason the findOneAndUpdate hook doesn't have access to the document, as far as I can tell.

我想这样做:

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();
});

但是由于某种原因,挂钩中的this不是文档,而是一个看起来毫无用处的Query对象.

But for some reason the this in the hook isn't the document, its a Query object which seems about useless.

我想念什么? 如何使用预钩子来更新findOneAndUpdate上的计数?

推荐答案

文档状态:

查询中间件在一个微妙但重要的方面不同于文档中间件:在文档中间件中,this表示要更新的文档.在查询中间件中,猫鼬并不一定要引用要更新的文档,因此this是指 query 对象而不是要更新的文档.

Query middleware differs from document middleware in a subtle but important way: in document middleware, this refers to the document being updated. In query middleware, mongoose doesn't necessarily have a reference to the document being updated, so this refers to the query object rather than the document being updated.

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

An update action generally updates a document that only exists in the database (it tells the MongoDB server: "find document X and set property X to value Z"), so the full document isn't available to Mongoose and, hence, you can't update the counts (which requires access to at least the arrays whose length you want to determine).

顺便说一句:为什么您仍然需要在架构中使用单独的*Count属性?如果要查询匹配特定大小的数组,可以使用 运算符直接在数组上.

As an aside: why do you need separate *Count properties in your schema anyway? If you want to query for arrays matching a certain size, you can use the $size operator on the arrays directly.

如果确实需要count属性,那么对于每次更新,您需要跟踪对每个数组所做的更改数量(以添加/删除的项目数为单位),并使用 $inc 运算符来调整计数.

If you really do need the count properties, then for each update, you need to track the number of changes you made to each of the arrays (in terms of the number of items added/deleted) and use the $inc operator to adjust the counts.

这篇关于猫鼬pre findOneAndUpdate挂钩问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆