Student01
Student01

Reputation: 109

How do I do atomic update using Bookshelf.js model?

For example, if I wanted to do something like the following in MySQL query:

update foo set bar = bar + ?;

How would I achieve this using Bookshelf.js model?

Upvotes: 3

Views: 4101

Answers (2)

Kessem Lee
Kessem Lee

Reputation: 1373

I couldn't get this to work as I expect it, but there's an increment method in the knex query builder library (http://knexjs.org/#Builder-increment) which is the underlying engine for this functionality in bookshelf.js

What I ended up doing was:

foo.forge().save({bar:bookshelf.knex.raw('bar + 1')},{method:"update"});

Upvotes: 3

uglycode
uglycode

Reputation: 3092

I'm not exactly sure what you mean by atomic, perhaps transactions? You can do that in bookshelf, there's a whole section about it: http://bookshelfjs.org/#Bookshelf-transaction

However, if you're just trying to update a field, you can do that easily as follows:

var idStationIWantToUpdate = 1;
new Station({'id': idStationIWantToUpdate}).save({
    route_name: 'my updated route name'
}).then(function(station) {
    res.json(station.toJSON());
});

The important part is that you instantiate a model with the corresponding ID, then when you call save, it automatically updates the existing record.

Upvotes: 4

Related Questions