skip to Main Content

I am trying to pre save and hash password with bcrypt in mongoose in my next.js project, but password still unhashed. i tryed every link in stackoverflow and didnt solve it, the password still saved unHashed.
mongoose version: 6.9.1

this is my users.model file:

import {
  models,
  model,
  Schema,
} from 'mongoose';
import bcrypt from 'bcrypt';

const UserSchema: Schema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  displayName: {
    type: String,
    required: true,
  },
  role: {
    type: String,
  },
});

UserSchema.pre('save', function (next) {
  console.log('Pre-Save Hash has fired.');
  let user = this;
  bcrypt.genSalt(10, (err, salt) => {
    if (err) console.error(err);
    bcrypt.hash(user.password, salt, (err, hash) => {
      user.password = hash;
      next();
    });
  });
});

const UserModel = models.Users || model('Users', UserSchema, 'users');

export default UserModel;

this is my adding function file:

import dbConnect from '@/utils/mongodb';
import UserModel from '@/models/user.model';
import { NextApiRequest, NextApiResponse } from 'next';
import { MongoError } from 'mongodb';
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // const { email, password } = req.query;
  try {
    dbConnect();
    const query = req.body;
    const newUser = new UserModel(query);
    const addedUser= await newUser.save(function (err: MongoError) {
      if (err) {
        throw err;
      }
    });
    res.status(200).json(addedUser);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Internal server error' });
  }
}

i cant see the ‘Pre-Save Hash has fired.’ in my console also..

2

Answers


  1. Chosen as BEST ANSWER

    thanks to all. The problem was in my dbconnect file!


  2. // You need to add user.isModified("password")
    userSchema.pre("save", function (next) {
      var user = this;
      if (user.isModified("password")) {
        bcrypt.genSalt(SALT_I, (err, salt) => {
          if (err) {
            return next(err);
          }
          bcrypt.hash(user.password, salt, (err, hash) => {
            if (err) {
              return next(err);
            }
            user.password = hash;
            next();
          });
        });
      } else {
        next();
      }
    });
    userSchema.methods.comparePassword = function (candidatePassword, cb) {
      bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
        if (err) return cb(err);
        cb(null, isMatch);
      });
    };
    
    
    
    // to make register end point
    import mongoose from "mongoose";
    import User from "../../../models/User";
    
    const dbConnect = async () => {
      mongoose
        .connect("mongodb://localhost:27017/test")
        .then(() => {
          console.log("Connected to mongoDb");
        })
        .catch((error) => {
          console.log(error);
        });
    };
    export default async function handler(req, res) {
      try {
        await dbConnect();
        const query = req.body;
        const newUser = new User(query);
        await newUser.save(function (err, result) {
          if (err) {
            throw err;
          } else {
            res.status(200).json(result);
          }
        });
      } catch (error) {
        console.error(error);
        res.status(500).json({ message: "Internal server error" });
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search