属性 "password" 类型文档不存在

Property "password" does not exists on type Document

我收到此错误 属性 "password" 在文档类型上不存在。那么谁能告诉我的代码是否有问题?

const userSchema = new mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  name: { type: String, required: true }
});

userSchema.pre("save", function save(next) {
  const user = this;
  if (!user.isModified("password")) {
    return next();
  }
  bcrypt.genSalt(10, (err, salt) => {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, (err: mongoose.Error, hash) => {
      if (err) {
        return next(err);
      }
      user.password = hash;
      next();
    });
  });
});

您需要根据 mongoose 文档在此处使用预保存挂钩添加类型,预挂钩定义为,

/**
 * Defines a pre hook for the document.
 */
pre<T extends Document = Document>(
  method: "init" | "validate" | "save" | "remove",
  fn: HookSyncCallback<T>,
  errorCb?: HookErrorCallback
): this;

如果您有如下所示的界面,

export interface IUser {
  email: string;
  password: string;
  name: string;
}

添加带有预保存挂钩的类型,

userSchema.pre<IUser>("save", function save(next) { ... }

在架构构造之后不久声明 .pre 函数,在声明具有已定义字段的接口之后。

我不知道这是否有帮助,因为这个问题现在已经很老了,但是我试过了

import mongoose, { Document } from 'mongoose';

const User = mongoose.model<IUser & Document>("users", UserSchema);

type IUser = {
    username: string
    password: string
}

mongoose.model 需要一个文档类型,而您想扩展该文档,因此统一这两种类型

您还可以将接口类型传递给架构本身。

import { model, Schema, Document } from 'mongoose';

const userSchema = new mongoose.Schema<IUser>({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  name: { type: String, required: true }
});

interface IUser extends Document{
  email: string;
  password: string;
  name: string;
}