You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在TypeScript中使用Mongoose时如何获取updateOne预中间件的更新文档

在Mongoose + TypeScript的updateOne预中间件中获取更新内容的替代方案

TypeScript无法识别updateOne预中间件中this.getUpdate()的核心原因是默认类型推断不足,以下是几种可行的替代方案:

1. 类型断言指定this的Query类型

通过手动将this断言为Mongoose的Query类型,即可正常调用getUpdate()方法:

import mongoose from 'mongoose';

// 假设你的Schema是针对YourDocument类型定义的
Schema.pre('updateOne', function (next) {
  const updateQuery = this as mongoose.Query<any, YourDocument>;
  const updateData = updateQuery.getUpdate();
  
  // 在这里处理更新数据
  console.log(updateData);
  
  next();
});

2. 直接访问更新内容(不推荐依赖私有属性)

虽然不推荐长期依赖私有属性,但如果只是临时解决问题,可以直接访问this._update(同样需要类型断言):

Schema.pre('updateOne', function (next) {
  const updateData = (this as any)._update;
  
  next();
});

3. 切换到findOneAndUpdate中间件(类型支持更友好)

如果业务逻辑允许,改用findOneAndUpdate的预中间件,TypeScript能自动识别this的类型,无需额外断言即可调用getUpdate():

Schema.pre('findOneAndUpdate', function (next) {
  const updateData = this.getUpdate();
  
  // 处理更新数据
  next();
});

4. 自定义扩展Query类型(严格类型检查)

如果需要更严格的类型约束,可以自定义接口扩展Mongoose的Query类型:

import mongoose from 'mongoose';

interface UpdateQueryWithGetUpdate<T> extends mongoose.Query<T, T> {
  getUpdate(): Partial<T>;
}

Schema.pre('updateOne', function (next) {
  const updateQuery = this as UpdateQueryWithGetUpdate<YourDocument>;
  const updateData = updateQuery.getUpdate();
  
  next();
});

内容的提问来源于stack exchange,提问作者mohammad tavassolian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:57:21