【问题标题】:Mongoose Schema hook and typescript: property does not existsMongoose Schema 钩子和打字稿:属性不存在
【发布时间】:2020-04-29 03:36:10
【问题描述】:

我正在尝试在typescript 中使用Mongoose 创建一个简单用户Schema

import mongoose, { Schema, Document } from "mongoose";
import bcrypt from "bcrypt";

const SALT_WORK_FACTOR = 10;

interface IUser extends Document {
  username: string;
  password: string;
  email: string;
  activeMembership: () => boolean;
  membershipExpires: Date;
  registeredOn: Date;
  lastLogin: Date;
  isAdmin: boolean;
}

const userSchema: Schema<IUser> = new Schema({
  username: { type: String, required: true },
  password: { type: String, required: true },
  email: { type: String, required: true },
  activeMembership: { type: Boolean, required: true, default: false },
  membershipExpires: { type: Number, required: true, default: 0 },
  registeredOn: { type: Date, required: true },
  lastLogin: { type: Date },
  isAdmin: { type: Boolean, required: true, default: false }
});

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

  bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
    if (err) throw err;
    bcrypt.hash(user.password, salt, (err, hash) => {
      if (err) throw err;
      user.password = hash;
      next();
    });
  });
});

但是打字稿一直在抱怨:

tsserver says Property 'password' does not exist on type 'Document'.

上线:

bcrypt.hash(user.password, salt, (err, hash) => {

和:

      user.password = hash;

我做错了什么?

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    尝试使用通用赋值&lt;IUser&gt;

    userSchema.pre<IUser>("save", function (next) {
      const user = this;
      if (!user.isModified("password")) return next();
    
      bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
        if (err) throw err;
        bcrypt.hash(user.password, salt, (err, hash) => {
          if (err) throw err;
          user.password = hash;
          next();
        });
      });
    });
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2019-05-05
      • 2019-10-28
      • 1970-01-01
      • 2020-01-28
      • 2018-09-27
      • 2017-03-02
      • 2021-09-07
      • 2015-12-26
      • 2017-09-29
      相关资源
      最近更新 更多