i have this model defined in sequelize:
"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define("User", {
username: DataTypes.STRING,
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isEmail: true
},
unique: {
args: true,
msg: 'Email address already in use!'
}
},
password: DataTypes.STRING
}, {
classMethods: {
generateHash: function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
},
},
instanceMethods: {
validPassword: function (password) {
return bcrypt.compareSync(password, this.password);
},
checkEmailExists: function (email) {
return email == this.email
}
}
});
return User;
}
i need to detect if a email aleady exist so i put a custom validation on the email, but then in my routing i have this:
var express = require('express');
var User = require('../../models').User;
var router = express.Router();
var sequelize = require('../../models/index');
/* GET users listing. */
router.post('/', function (req, res, next) {
if (JSON.stringify(req.body) == "{}") {
return res.status(400).json({ Error: "Register request body is empty" });
}
if (!req.body.email || !req.body.username || !req.body.password) {
return res.status(400).json({ Error: "Missing fields for registration" });
}
var password = User.generateHash(req.body.password);
User.create({
username: req.body.username,
email: req.body.email,
password: password
}).then(function () {
return res.status(200).json({ message: "user created" });
}).catch(function (err) {
return res.status(400).json({ message: "issues trying to connect to database" });
})
});
module.exports = router;
seems like it is entering the catch because it detects that the email already exist, but i want to display the message that is inside the model and not that catch that can mean something else, how can i display it there in my routing?
via Antonio Costa
No comments:
Post a Comment