Bookshelf.js,在fetchAll()方法之后更新

Bookshelf.js, update after fetchAll() method

本文关键字:方法 之后 更新 fetchAll js Bookshelf      更新时间:2023-09-26

使用bookforf.js,我试图获得一组对象,然后将它们全部更新。

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

我试图在Bookshelf.js中实现的功能与SQL:中的功能相当

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

CCD_ 1显然是来自CCD_ 2参数的值。

SQL似乎比Bookshelf.js方法简单得多。

有没有更好的方法可以同时更新这些行,而不是在.save()方法上循环?

您的解决方案看起来很可靠,但当然还有更好的方法。例如,您可以明确指定要执行更新(http://bookshelfjs.org/#Model-实例保存),然后可以使用knex查询生成器并限制要更新的条目(http://knexjs.org/#Builder-其中In)。

所以,把所有的东西放在一起,试试这样的东西(这是我为了测试解决方案而执行的一些演示示例):

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

希望这能有所帮助!

更新/插入怎么样?有什么更雄辩的方法可以做到这一点?

yield Promise.map data, (oneEvent)->
  eventModel = new Event oneEvent
  eventModel.fetch().then (fromDB) ->
    return do eventModel.save if not fromDB?
    fromDB.save oneEvent