属性“密码”在文档类型上不存在

Bar*_*ter 4 bcrypt mongoose typescript

我收到此错误文档类型上不存在属性“密码”。那么谁能说出我的代码是否有问题?

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();
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

小智 7

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

import mongoose, { Document } from 'mongoose';

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

type IUser = {
    username: string
    password: string
}
Run Code Online (Sandbox Code Playgroud)

mongoose.model 需要一个 Document 类型,并且你想扩展那个文档,因此统一这两种类型


Shi*_*dey 5

您需要按照猫鼬文档在此处添加带有预保存钩子的类型,预钩子定义为,

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

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

export interface IUser {
  email: string;
  password: string;
  name: string;
}
Run Code Online (Sandbox Code Playgroud)

使用预保存钩添加类型,

userSchema.pre<IUser>("save", function save(next) { ... }
Run Code Online (Sandbox Code Playgroud)

  • 来自猫鼬回购,https://github.com/Automattic/mongoose/issues/5046#issuecomment-412114160 (2认同)

sam*_*war 5

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

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;
}
Run Code Online (Sandbox Code Playgroud)