DeadEye DeadEye - 2 years ago 344
Javascript Question

Bookshelf.js, update after fetchAll() method

Using bookshelf.js, I'm trying to get a set of objects and then update them all.

function markPostsAsSent(postsIds) {
return new Promise((resolve, reject) => {
// Get posts
.where({ id: postsIds })
.then(posts => {
// For each post, update sent value, post =>{ is_sent: true }))
.then(() => {
}, err => {
reject(Dependencies.getException(exceptionName, 500, 'POST_UPDATE_ERROR', new Error(), err));
}, err => {
reject(Dependencies.getException(exceptionName, 500, 'POST_FETCH_ERROR', new Error(), err));

What I'm trying to achieve in Bookshelf.js is equivalent to this in SQL :

UPDATE searches_posts
SET is_sent = true
WHERE id IN (1, 2, 3, 4);

(1, 2, 3, 4)
are obviously values from

The SQL seems so much more simpler than the Bookshelf.js method.

Is there a better way to update these rows all at the same time instead of looping on .save() method ?

Answer Source

Your solution seems solid, but of course, there is a better way. E.g., you can specify explicitly that you want to perform an update ( and you can tap into the knex query builder and limit which entries you want to update (

So, putting everything together, try something like this (this is some demo example I performed in order to test the solution):

new Person().query(function(qb) {
    qb.whereIn('id', [2, 4]);
    number_of_children: 5
}, {
    method: 'update'
}).then(function() {
    //Entries with ids 2 and 4 have been updated!

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download