2016-05-16 61 views
1

我想弄清楚如何使用非实例对象最好地更新一行。用例(我想)很常见。基本上,我有一个保存API方法:从Sequelize中的非实例更新

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方法,但是我不想使用它,因为我想我的电话给新返回创建实例,而不必在插入/更新后找到它们)。

回答

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)); 
} 

它会找到或创建新实例并返回它。

+0

是的,但更新?我需要它在数据库中创建或更新。看起来你的代码只会创建... – pQuestions123

+0

啊,我的坏会修改。 – drinchev

+0

但是,您的代码不需要两个查询来更新实例。我的问题是什么(我相信只有一个查询)。 – pQuestions123