I'm trying to make an login/signup system with authentication. Im using Nodejs with bcrypt to encrypt the data.
My problem is that the hashed pw does not get stored into the DB.
Here is my signup route,
router.post('/signup', (req, res, next) => {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err,
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash,
});
user
.save()
.then((result) => {
console.log(result);
res.status(201).json({
message: 'User created',
});
})
.catch((err) => {
console.log(err);
res.status(500).json({
error: err,
});
});
}
});
});
Schema file
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
email: {
type: String,
required: true,
unique: true,
match: /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/,
password: { type: String, required: true },
},
});
module.exports = mongoose.model('User', userSchema);
User model
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash,
});
I think the problem has something with how it runs asynch. I manage to console log the hash. What could I try to debug this problem for myself? Any pointers would be appreciated.