簡體   English   中英

當我嘗試保存 model 時,user.save() 不是 function

[英]user.save() is not a function when i am trying to save the model

  const user = User.findOne({email:req.body.email});
    
      if(!user){
        return next(new ErrorHander("User not found",404));
    
      }
 const resetToken = user.getResetPasswordToken

  await user.save({ validateBeforeSave: false });
  

我不知道為什么 user.save 在 mern mongodb 中不起作用我有相同的代碼為其他人工作但不適合我

我所做的是我通過在第一行中觸發查詢來獲取用戶,在該用戶之后我應該能夠在這里使用 user.save() function 但遺憾的是它給出了錯誤

//這是我的 model 架構

const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcryptjs");
const crypto = require("crypto")

const jwt = require("jsonwebtoken");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "please Ente the your name"],
  },
  email: {
    type: String,
    required: [true, "Please Enter the email"],
    unique: [true],
    validate: [validator.isEmail, "Please Enter a valid email"],
  },
  password: {
    type: String,
    required: true,
    minlength: [8, "Passwaord must be more that 8 characters"],
    select: false,
  },
  avatar: {
    public_id: {
      type: String,
      required: true,
    },
    url: {
      type: String,
      required: true,
    },
  },
  role: {
    type: String,
    default: "user",
  },
  resetPasswordToken: String,
  resetPasswordTokenExpire: Date,

  createdAt: {
    type: Date,
    default: Date.now,
  },
});

userSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }

  this.password = await bcrypt.hash(this.password, 10);
});

userSchema.methods.comparePassword = async function (password) {
  return await bcrypt.compare(password, this.password);
};

userSchema.methods.getJWTToken = function () {
  return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRE,
  });
};

// compare password

// userSchema.methods.comparePassword = async function(enterPass){
//     return await bcyrypt.compare(enterPass,this.password)
// }

// Reset Password

userSchema.methods.getResetPasswordToken = function(){
  const resetToken = crypto.randomBytes(20).toString("hex");
  this.resetPasswordToken = crypto.createHash("sha256").update(resetToken).digest("hex");
  this.resetPasswordTokenExpire = Date.now +15*60*1000;

  return resetToken;
}

module.exports = mongoose.model("User", userSchema);

User.findOne 將返回 Promise。 所以你需要添加 await 關鍵字。

const user = await User.findOne({email:req.body.email});
    
      if(!user){
        return next(new ErrorHander("User not found",404));
    
      }
 const resetToken = user.getResetPasswordToken

  await user.save({ validateBeforeSave: false });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM