简体   繁体   English

Mongoose 中的 ._doc

[英]._doc in Mongoose

I have this js code我有这个js代码

app.post('/auth', async (req, res) => {
    try {
        const user = UserModel.findOne({email: req.body.email}).exec()
        if (!user) return res.status(404).json({
            message: 'Not find user'
        })
        const isValidPassword = bcrypt.compare(req.body.password,user._doc.passwordHash)
        if (!isValidPassword) return res.status(404).json({
            message: 'Incorrect password'
        })
    }
    catch (err) {
        console.log(err)
        res.status(500).json({
            message: 'error'
        })
    }
})

And I have this Schema我有这个架构

import mongoose from 'mongoose'

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    surname: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    passwordHash: {
        type: String,
        required: true
    },
    telegramUrl: {
        type: String,
        required: true
    },
    avatarUrl: String
},
    {
        timestamps: true
    }
)

export default mongoose.model('User', userSchema)

In this line在这一行

const isValidPassword = bcrypt.compare(req.body.password,user._doc.passwordHash)

I have error: Cannot read properties of undefined (reading 'passwordHash').我有错误:无法读取未定义的属性(读取“密码哈希”)。 Why am I getting an error?为什么我会收到错误消息? He writes to me that._doc undefined but why?他写信给我 that._doc undefined 但为什么呢? Help me please请帮帮我

use these two methods in your schema在您的架构中使用这两种方法

  const bcrypt = require("bcrypt");
  // Create Hash Salt Password ..
  userSchema.pre("save", async function (next) {
  if (!this.isModified("passwordHash")) return next();
     this.passwordHash = await bcrypt.hash(this.passwordHash, 12);
    next();
  });
  // Compare Password ...
   userSchema.methods.comparePassword = function (passwordHash) {
   return bcrypt.compareSync(passwordHash, this.passwordHash);
  };

And in your auth code在您的身份验证代码中

app.post('/auth', async (req, res) => {
try {
    const user = await UserModel.findOne({email: req.body.email}).exec()
    if (user) {
       res.status(400).json(
         { message: 'User already register'})
        }
       else{
         const newuser = New User({
           name: req.body.name,
           // also write other schema fields
           }
          const res = await newuser.save();
          console.log(res)
    
catch (err) {
    console.log(err)
    res.status(500).json({
        message: 'error'
    })
}

}) })

I hope this should resolve your problem我希望这能解决你的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM