Search code examples
knex.jsbookshelf.js

Bookshelf.js: bulk update


I'm editing some records with Bookshelf.js. The number of records might be quite high. I would like to either bulk update these records, or at least run the update loop inside the context of a transaction, for the sake of speed. How do I do this with Bookshelf.js? If this is not possible, how do I do it with Knex?

Here is my current update function:

new Endpoint()
                    .where({
                        'organization_id': orgId,
                        'id': endpointId
                    })
                    .save(updatedEndpoint, {patch: true})
                    .then((endpoint) => {
                        Endpoint
                            .where({
                                'organization_id': orgId,
                                'id': endpointId
                            })
                            .fetch({withRelated: ['settings', 'organization']})
                            .then((newEndpoint) => {
                                ReS(res, {
                                    endpoint: newEndpoint
                                }, 200);
                            })
                            .catch(e => TE(e));
                    })
                    .catch(e => TE(e));

Solution

  • You'll have to resort to the query builder (knex.js) for bulk updates:

    Endpoint
      .query()
      .whereIn('id', [1, 2, 3, /* ... */])
      .andWhere({'organization_id': orgId})
      .update({whatever: 'a value'})
      .then(function(results) {
        // ...
      })
    

    See issue #402 for more info.