bipin
bipin

Reputation: 419

insert array of data in loopback

i m using loopback and don't know how to insert array of data using sing api for eg i have data like

 view: [ true, false, false ],
 edit: [ false, true, false ],
 update: [ false, false, true ],
 product: [ 1, 2, 3]

now i want to insert data like this in table

  product | view | edit |update 
----------------------------------
     1    |true  |false |false 
     2    |false |false |true  
     3    |false |false |true  

i know i can use for loop but don't know where to use i.e whether this is possible in remote hook method or remote method can can one suggest me idea how to do this

Upvotes: 1

Views: 2076

Answers (1)

user8120138
user8120138

Reputation:

http://apidocs.loopback.io/loopback/#persistedmodel-create

PersistedModel.create([data], callback) Create new instance of Model, and save to database.

Arguments Name Type Description [data] Object or Array.
Optional data argument. Can be either a single model instance or an array of instances.

Create can take an array of instances. POST with an array in the request body and it will insert them all.

EDIT In your case I think you have to create a remote method. Model specific validation will fire after before save, but the default POST method validation will not allow you to submit an array of arrays. Here's some example code, replace assembled with however you create your array of objects from your array of arrays

  MyModel.assembleAndInsert = async (data, cb) => {
    // Assemble the data
    let assembled = [{name: 'iecream'}];
    debugger;
    let result = await MyModel.create(assembled);
    cb(null, result);
  };

  MyModel.remoteMethod('assembleAndInsert', {
    http: {
      path: '/assembleAndInsert',
      verb: 'post',
      status: 200,
      errorStatus: 400,
    },
    accepts: [{ arg: 'data', type: 'array', http: { source: 'body' } }],
    returns: {
      arg: 'created',
      type: 'Array',
    },
  });

Upvotes: 2

Related Questions