skip to Main Content

I am trying to save password in MongoDB but have error:

Error: User validation failed: password: Path `password` is required.

Model:

const {Schema, model} = require('mongoose');

const UserSchema = new Schema({
    email: {type: String, unique: true, required: true},
    password: {type: String, required: true},
    isActivated: {type: Boolean, default: false},
    activationLink: {type: String},
})

module.exports = model('User', UserSchema)

create user:

        const bcrypt = require('bcryptjs');
        const UserModel = require('../models/user-model');
        ...
        const hashPassword = await bcrypt.hash(password, 10);
        console.log(`email => ${email} pass => ${hashPassword}`);
        const user = await UserModel.create({email, hashPassword});

Log shows that password hash created:

email => [email protected] pass => $2a$10$4IV2Q0ZncWHInfT89Fwl.eCxCgvykvY.uqlvq0GNSeDJ/6Q83T7nK

2

Answers


  1. const user = await UserModel.create({email, hashPassword});

    If you pass hashPassword variable, it will take as hashPassword field.
    Change your code like this:

    const hashPassword = await bcrypt.hash(password, 10);
    const user = await UserModel.create({email, password: hashPassword});
    
    Login or Signup to reply.
  2. Re-create your model using these lines of code

    const mongoose = require('mongoose')
    const bcrypt = require('bcryptjs')
    
    const userSchema = mongoose.Schema(
    {
      email: {
        type: String,
        required: true,
        lowercase: true,
        trim: true
     },
     password: {
      type: String,
      required: false,
      minlength: 8
     },
     activationLink: {
      type: String,
      trim: false
     },    
     isActivated: {
       type: Boolean,
       default: false
     }
     },{
      timestamps: true
     }
    )
    
    userSchema.methods.isPasswordMatch = async function (password) {
     const user = this
     return bcrypt.compare(password, user.password)
    }
    
    userSchema.pre('save', async function (next) {
      const user = this
      if (user.isModified('password')) {
       user.password = await bcrypt.hash(user.password, 8)
      }
     next()
    })
    
    const User = mongoose.model('user', userSchema)
    
    module.exports = User
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search