Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert or update(upsert) in loopback application

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..
like image 906
Subburaj Avatar asked Jul 01 '16 06:07

Subburaj


People also ask

What is repository in loopback?

A Repository represents a specialized Service interface that provides strong-typed data access (for example, CRUD) operations of a domain model against the underlying database or service. Note: Repositories are adding behavior to Models.

How do I check lb4 version?

Use lb4 --version (or lb4 -v ) to print out version information to include in bug reports, for example: $ lb4 -v @loopback/cli version: 1.8. 1 @loopback/* dependencies: - @loopback/authentication: ^1.0.

What is persisted model?

PersistedModel is the base class for models connected to persistent data sources such as databases and is also the base class for all built-in models (except Email). It provides all the standard create, read, update, and delete (CRUD) operations and exposes REST endpoints for them.


1 Answers

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);  
    });
like image 195
conradj Avatar answered Sep 25 '22 23:09

conradj