【问题标题】:Property "password" does not exists on type Document文档类型上不存在属性“密码”
【发布时间】:2019-05-07 18:22:42
【问题描述】:

我收到此错误“文档”类型不存在属性“密码”。那么任何人都可以判断我的代码是否有问题?

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

【问题讨论】:

标签: typescript mongoose bcrypt


【解决方案1】:

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

/**
 * 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) { ... }

【讨论】:

  • 你也可以评论一下提到这个的链接。没找到
  • @Barometer 很高兴,它有帮助!请考虑接受我的回答。
  • 我在import { Document } from 'mongoose'; 之后将export interface IUser 更改为export interface IUser extends Document {,这样就不需要在上面定义pre&lt;T extends Document = Document&gt;(
【解决方案2】:

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

import mongoose, { Document } from 'mongoose';

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

type IUser = {
    username: string
    password: string
}

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2020-08-13
        • 2021-05-04
        • 2021-05-29
        • 2023-03-08
        • 2019-09-07
        • 2020-03-06
        • 2017-07-05
        • 2021-05-09
        • 2022-07-28
        相关资源
        最近更新 更多