So I have this code:
//defining partner
var Partner = sequelize.define('Partner', {
order: Sequelize.INTEGER,
image: Sequelize.STRING,
}, {
tableName: 'partners',
});
//creating partner instance
var partner=Partner.build();
partner.save().success(function(newpartner){
console.log(newpartner.id);
});
When this code gets executed, 2 instances of partner are inserted to the database. The second one is pushed when I access id
property of partner
.
Here is the log from the console:
Executing (default): INSERT INTO `partners` (`updatedAt`,`createdAt`) VALUES ('2014-08-16 13:13:26','2014-08-16 13:13:26');
Executing (default): INSERT INTO `partners` (`id`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'2014-08-16 13:13:26','2014-08-16 13:13:26');
I need to get id of the partner and send it to client after persisting it to the database. How do I do it properly?
For now I just access id
property without invoking save()
, since it saves object anyway. However this is not documented. Is there a proper way to do it?
I managed to isolate the problem.
My mistake came from reading docs not thoroughly enough. Apparently setting associated object pushes entity to the Database (unlike in Doctrine, for example). So my entity was saved during execution of the following code (not included in the question):
Partner.setManager(manager);
Where Manager
is an entity in oneToMany relationship to Partner.
So the solution was to remove the save() call and use the success
callback from the setManager()