续编upsert

我需要得到插入/更新logging的id时使用.upsert()在sequelize。

.upsert()返回一个布尔值,指示行是否被创build或更新。

 return db.VenueAddress.upsert({ addressId:address.addressId, venueId: venue.venueId, street: address.street, zipCode: address.zipCode, venueAddressDeletedAt: null }).then(function(test){ //test returned here as true or false how can i get the inserted id here so i can insert data in other tables using this new id? }); 

我想要upsert返回创build或更新的对象。 这并不是因为只有PGSQL直接支持它,显然。

所以我创build了一个天真的实现,可能会以非高性能的方式,并可能与各种竞争条件,做到这一点:

 Sequelize.Model.prototype.findCreateUpdate = function(findWhereMap, newValuesMap) { return this.findOrCreate({ where: findWhereMap, defaults: findWhereMap }) .spread(function(newObj, created) { // set: for(var key in newValuesMap) { newObj[key] = newValuesMap[key]; } return newObj.save(); }); }; 

尝试在游戏中创build/更新移动时的用法(人为示例警报!):

 models.Game .findOne({where: {gameId: gameId}}) .then(function(game) { return db.Move.findCreateUpdate( {gameId: gameId, moveNum: game.moveNum+1}, {startPos: 'kr4', endPos: 'Kp2'} ); }); 

詹梅尔说:

这只能由postgres支持,所以为了保持API在方言中的一致性,这是不可能的。

请参阅: https : //github.com/sequelize/sequelize/issues/3354

这对我来说是有效的:

 Model.upsert({ title:your title, desc:your description, location:your locations }).then(function (test) { if(test){ res.status(200); res.send("Successfully stored"); }else{ res.status(200); res.send("Successfully inserted"); } }) 

它会检查数据库find您的主键。 如果它发现,那么它将更新数据,否则将创build一个新的行/插入到一个新的行。

我知道这是一个旧的职位,但万一这有助于任何人

 const upsert = async (model: any, values: any, condition: any): Promise<any> => { const obj = await model.findOne({ where: condition }) if (obj) { // only do update is value is different from queried object from db for (var key in values) { const val = values[key] if (parseFloat(obj[key]) !== val) { obj.isUpdatedRecord = true return obj.update(values) } } obj.isUpdatedRecord = false return obj } else { // insert const merged = { ...values, ...condition } return model.create(merged) } } 

我自己解决如下:

 return db.VenueAddress.upsert({ addressId:address.addressId, venueId: venue.venueId, street: address.street, zipCode: address.zipCode, venueAddressDeletedAt: null },{individualHooks: true}).then(function(test){ // note individualHooks });