Reputation: 4608
I'm new to node.js, and is using Express and Sequelize to build a restful api. For now I just need to create a user by the following code:
router.post('/preregister', function(req, res, next) {
models.users.create(req.body, function(err, user) {
console.log('req: ' + req.body);
if (err) res.json(err);
res.json(user);
});
});
The system output the sql statement, and I can see that the data is created by querying database, but then the server hangs there and does not do anything any more, not even printing out the 'req' line right before the if statement, which looks like the function(err, user) part is never touched. Looks like something fundamental is wrong. But what is missing??
The users model is defined as below:
"use restrict";
module.exports = function(sequelize, Sequelize) {
var users = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
isUnique: true,
field: 'id'
},
email: {
type: Sequelize.STRING,
isUnique: true,
allowNull: false,
validate: {
isEmail: true
},
field: 'email'
}
}, {
freezeTableName: true
});
return users;
};
Upvotes: 0
Views: 155
Reputation: 203241
Sequelize uses (a modified version of) the bluebird promises library, which means that this should work:
router.post('/preregister', function(req, res) {
models.users.create(req.body).then(function(user) {
res.json(user);
}).catch(function(err) {
console.error(err);
res.sendStatus(500);
});
});
Upvotes: 1
Reputation: 594
Sequelize
is Using Promises
in it's latest versions
router.post('/preregister', function(req, res, next) {
var user = models.users.build(req.body);
user.save()
.complete(function(err) {
if (err) return next(err);
res.json(user);
});
});
Upvotes: 1
Reputation: 12293
router.post('/preregister', function(req, res, next) {
models.users.create(req.body, function(err, user) {
if (err) res.json(err);
res.json(user);
});
});
Upvotes: 0