鍍金池/ 問(wèn)答/數(shù)據(jù)庫(kù)  HTML/ 求助,Sequelize的upsert寫(xiě)法問(wèn)題

求助,Sequelize的upsert寫(xiě)法問(wèn)題

按照文檔關(guān)于upsert的寫(xiě)法是:

upsert(values, [options]) -> Promise.<created>

創(chuàng)建或更新一行。如果匹配到主鍵或唯一約束鍵時(shí)會(huì)進(jìn)行更新。

名稱(chēng) 類(lèi)型 說(shuō)明
values Object
[options] Object
[options.validate=true] Boolean 插入前進(jìn)行驗(yàn)證
[options.fields=Object.keys(this.attributes)] Array 要插入/更新字段。默認(rèn)全部
[options.transaction] Transaction 在事務(wù)中執(zhí)行查詢(xún)

嘗試寫(xiě)了一段,查找數(shù)據(jù),如果沒(méi)有創(chuàng)建,如果有則更新。

model.upsert({
          id: 2,
          name: find.name
          count: 1,
        }, {
          fields: { count: Sequelize.literal('`count` +1') },
        });

執(zhí)行總報(bào)錯(cuò): nodejs.TypeError: fields[Symbol.iterator] is not a function

是我的語(yǔ)法錯(cuò)了么,求正確寫(xiě)法。

回答
編輯回答
不二心
  • fields的類(lèi)型是Array,表示第一個(gè)參數(shù)內(nèi)的部分字段名(例fields['count']的話,upsert只添加/更新count字段)
  • 正確的寫(xiě)法:
model.upsert({
    id: 2,
    name: find.name
    count: 0
})
.then(inserted => { // 此參數(shù)表示是添加還是修改,true添加,false修改
    model.increment('count', {
        by: 2,
        where: {id: 2}
    });
});
2018年2月17日 21:57