从Sequelize中的非实例更新

updating from non-instance in Sequelize

本文关键字:实例 更新 Sequelize      更新时间:2023-09-26

我正试图找出如何使用非实例对象来最好地更新行。这个用例(我想)很常见。基本上,我有一个保存API方法:

function save(req, res, next) {
    var instance = req.body;
    var promise;
    if (instance[this.pkeyProperty]) {
        promise = this.model.update(instance, {
            [this.pkeyProperty]: instance[this.pkeyProperty],
            returning: true
        })
        .then((affectedCount, affectedRows) => affectedRows[0])
    }
    else {
        promise = this.model.create(instance);
    }
    promise
        .then((instance) => res.ok(instance))
        .catch(err => res.serverError(err));
}

想知道这是否是一种合适的insertOrUpdate方法(我看到了upstart方法,但我不想使用它,因为我希望我的调用返回新创建的实例,而不必在插入/更新后找到它们)。

在您的情况下,我将使用findOrCreate方法

function save(req, res, next) {
    var instance = req.body;
    this.model.findOrCreate( { 
        where : { [this.pKeyProperty] : instance[this.pKeyProperty] },
        defaults : instance
    }).spread( (result, created) => {
       return created ? result : result.update(instance) 
    }).then( instance => {
       res.ok( instance );
    }).catch( err => res.serverError(err) );
}

它将查找或创建新实例并返回。