node.js - Unable to store bcrypt hashed password from JSON into mongodb using mongoose -


i'm unable store bcrypt hashed password json mongodb using mongoose. think there mistake in implementation of setpassword schema method. i've replaced 'bcrypt' 'crypto' implementation , worked fine. hashed string stored in database. unable 'bcrypt'

my model.js implementation

const mongoose = require('mongoose'); const bcrypt = require('bcrypt');  const schema = mongoose.schema;  // user schema const userschema = new schema({   username: {     type: string,     index: true   },   password: {     type: string   },   email: {     type: string   },   name: {     type: string   } });  userschema.methods.setpassword =  function(password) {   const saltrounds = 10;   bcrypt.hash(password, saltrounds, function(err, hash) {     this.password = hash;   }); };  mongoose.model('user', userschema); 

my router controller implementation

const passport = require('passport'); const mongoose = require('mongoose'); const user = mongoose.model('user');  const register = (req, res) => {    const newuser = new user();    newuser.name = req.body.name;   newuser.email = req.body.email;   newuser.username = req.body.username;   newuser.setpassword(req.body.password);    newuser.save((err) => {     // validations error     if (err) {       res.status(400).json(err);       return;     }      res.status(200).json({       success: true,       message: 'registration successful'     });    }); }; 

this points bcrypt.hash not userschema object.

userschema.methods.setpassword =  function(password) {   const saltrounds = 10;   var = this;   bcrypt.hash(password, saltrounds, function(err, hash) {     that.password = hash;   }); }; 

update: use callback or promises

userschema.methods.setpassword =  function(password, cb) {   const saltrounds = 10;   var = this;   bcrypt.hash(password, saltrounds, function(err, hash) {     that.password = hash;     cb();   }); };  newuser.setpassword(req.body.password, function(){     //rest of code }); 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -