I'm trying to use Sequelize beforeCreate hook to create Card instance for my User. For some reason hook is not fired:
"use strict";
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
email: DataTypes.STRING,
hash: DataTypes.STRING(1024),
salt: DataTypes.STRING(512),
activationKey: DataTypes.STRING,
resetPasswordKey: DataTypes.STRING
}, {
hooks: {
beforeCreate: function(user, options, cb) {
console.log('[ORM]: hook `beforeCreate` for model User...')
models.Card
.create({
name: user.name,
url: null
})
.then(function(card) {
user.addCard(card).then(function() {
cb(null, user)
})
})
.catch(function(err) {
console.log(err)
cb(null, user)
})
}
},
classMethods: {
associate: function(models) {
// associations can be defined here
User.hasMany(models.Card)
}
}
});
return User;
};
Testing:
db.sequelize.sync().then(function() {
console.log('[INFO]: database synced')
User.create({
email: "helloworld@example.com",
name: "John Dow"
})
});
User is created, but Card — not, hook is not fired:
[INFO]: database synced
Executing (default): INSERT INTO "Users" ("id","email","updatedAt","createdAt") VALUES (DEFAULT,'helloworld@example.com','2015-04-20 09:22:50.388 +00:00','2015-04-20 09:22:50.388 +00:00') RETURNING *;
Any ideas, what I'm doing wrong? Thank you!
Aucun commentaire:
Enregistrer un commentaire