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..
"id": { "type": "string", "id": true },"bbid": { "type": "string", "id": true }
– Annattoid
in your data sent toupsert
? – Annattoupsert
should know insert or update?? So you should haveid
to do that. To clarify, where you call upsert? – Annattoapp.models.modelname.upsert({bbid:bb.id, saved: Saved, userid:1} ,function(err, res){ });
here you should provideid
. If not, soupsert
doesn't findid
and calls insert. Maybe you should think about what is(are) id's in that model. What key(s) do you want for that model? – Annattoid
and setbbid
as id of the model."properties": { "id": false, "bbid": { "type": "number", "id": true }
– Annattoconradj
solution is working.. Thanks for your valuable time.. – Mihrab