在loopback中插入数据数组

时间:2018-04-09 13:45:07

标签: loopbackjs strongloop

我使用环回并且不知道如何使用sing api插入数据数组,例如我有像

这样的数据
 view: [ true, false, false ],
 edit: [ false, true, false ],
 update: [ false, false, true ],
 product: [ 1, 2, 3]

现在我想在表格

中插入这样的数据
  product | view | edit |update 
----------------------------------
     1    |true  |false |false 
     2    |false |false |true  
     3    |false |false |true  

我知道我可以使用for循环但不知道在哪里使用,即在远程钩子方法或远程方法中是否可以这样可以建议我如何做到这一点

1 个答案:

答案 0 :(得分:2)

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

  

PersistedModel.create([data],callback)创建Model的新实例,   并保存到数据库。

     

参数名称类型描述[data]对象或数组。
  可选的数据参数。 可以是单个模型实例,也可以是   实例数组

Create可以获取一组实例。 POST在请求正文中有一个数组,它会将它们全部插入。

EDIT 在你的情况下,我认为你必须创建一个远程方法。模型特定验证将在before save之后触发,但默认的POST方法验证将不允许您提交数组数组。这是一些示例代码,用你自己的数组数组创建对象数组替换assembled

  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',
    },
  });