Reputation: 2164
I am new to Sequelize, so I have a very simple, perhaps trivial question. Consider the example on the docs:
var project = Project.build({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
})
var task = Task.build({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
})
I want to make sure I either save both or none of them. How do I do that? In other words, how do I atomically perform creat/update operations on multiple tables?
Upvotes: 2
Views: 2637
Reputation: 28788
In short, use transactions:
sequelize.transaction().then(function (t) {
return sequelize.Promise.all([
Project.create({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
}, { transaction: t }),
Task.build({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
}, { transaction: t })
]).then(function onFulfilled (project, task) {
return t.commit();
}, function onRejected(err) {
return t.rollback();
});
});
In the latest version (2.0-rc2) this can also be written more succinctly as:
sequelize.transaction(function (t) {
return sequelize.Promise.all([
Project.create({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
}, { transaction: t }),
Task.build({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
}, { transaction: t })
]);
});
By passing a callback to the transaction
instead of calling then
. The callback returns a promsie chain, and the transaction is commited or rolled back, depending on the success of the returned promise. Meaning that if any of the operations passed to Promise.all
fail, the transaction will be rolled back.
Upvotes: 6