我试图弄清楚如何使用非实例对象最好地更新行。用例(我猜)很常见。基本上,我有一个保存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的合适方式(我看到了upsert方法,但是我不想使用它,因为我希望我的调用返回新创建的实例而不必在插入/更新后找到它们)
答案 0 :(得分:1)
在您的情况下,我会使用findOrCreate
method
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) );
}
它将找到或创建新实例并将其返回。