insert or update(upsert) in loopback application
You can use the findOrCreate
method as follows:
app.models.modelname({where: {bbid:bb.id} }, {bbid:bb.id, saved: Saved, userid:1}, function(err, instance) {
if (err){
cb(null, err);
}
cb(null, instance);
});
There are two methods in loopback one is simple upsert and second is upsertWithWhere.To insert or update based on where condition you must use upsertWithWhere method upsert only inserts the data. you are using
app.models.modelname.upsert({bbid:bb.id, saved: Saved, userid:1}
,function(err, res){});
instead use
app.models.modelname.upsertWithWhere({bbid:bb.id, saved: Saved, userid:1}
,function(err, res){});
this will solve your problem.
note: this only updates single instance.If multiple instances are returned in where condition result it will throw an error.