I developed an API using Loopback framework, in that i have to insert or update
to a table.
My table looks like below:
userid bbid saved id(PK)
1 5 1000 1
So when next time if(bbid = 5) it should update the above row, if bbid =5 is not there it should insert into the above table.
I tried the following:
app.models.modelname.upsert({
bbid: bb.id,
saved: Saved,
userid: 1
}, function(err, res) {});
EDIT for COMPOSITE ID:
app.models.modelname.upsert({
bbid: vvvv.bbid,
userid: 1,
saved: amountSaved
}, function(err, res) {});
Also gone through Loopback doc it says
upsert - checks if the instance (record) exists, based on the designated
ID property, which must have a unique value; if the instance already exists,
the method updates that instance. Otherwise, it inserts a new instance.
But in my case it should check for bbid not id
But its inserting everytime. Please share your ideas. Thanks in advance
EDIT FOR UPSERT:
My process is as follows:
Fetch from table1 and loop that response and calculate the saved and upsert it into another table(table2 (this is where upsert should happen)). Also the fetching from table1 will happen frequently so suppose consider if is happens 2nd time it should update the already present bbid..
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);
});