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

Mongoose .pre('save')钩子报错:TypeScript类型不兼容求助

解决方案

1. 修正中间件执行逻辑错误

你的代码最后一行return next;存在错误,必须调用next()函数才能触发后续中间件或保存操作,否则整个流程会卡住,无法完成用户数据的保存:

userSchema.pre("save", async function (next) {
  let user = this as UserDocument;
  if (!user.isModified("password")) return next();

  const salt = await bcrypt.genSalt(config.get("saltWorkFactor"));
  const hash = await bcrypt.hash(user.password, salt);
  user.password = hash;
  // 调用next()而非返回函数本身
  return next();
});

2. 解决TypeScript类型错误

出现"Argument of type '"save"' is not assignable to parameter of type 'RegExp | "insertMany"'.ts"错误,通常是以下原因导致:

  • 版本兼容问题:确保mongoose和@types/mongoose版本匹配,建议升级到最新稳定版(如Mongoose 7.x+),旧版本的类型定义可能存在事件类型限制。
  • Schema定义错误:保证你的Schema是mongoose.Schema的正确实例,且泛型参数正确关联UserDocument:
import mongoose, { Document, Schema } from 'mongoose';

// 正确定义用户文档类型
interface UserDocument extends Document {
  password: string;
  // 其他用户字段
}

// 创建Schema时指定泛型
const userSchema = new Schema<UserDocument>({
  password: { type: String, required: true }
  // 其他字段配置
});
  • 避免错误导入:确认未误导入其他库的Schema类型,所有相关类型均来自mongoose包。

3. 额外验证方案

如果上述步骤无效,可尝试显式指定钩子的事件与参数类型:

import { HookNextFunction } from 'mongoose';

userSchema.pre<UserDocument>("save", async function (next: HookNextFunction) {
  // ... 原有逻辑代码 ...
  next();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:51:55