【问题标题】:Loopback: remote method - multiple updateLoopback:远程方法 - 多次更新
【发布时间】:2018-06-06 20:15:13
【问题描述】:

所以,我想要一个函数,用 orderId 重新排序我的记录

我正在传递一个这样的数组:

[
  {id: "5b1007aeb39c961a40540db9", orderId: 0},
  {id: "5b150352184eb8471c34cf7c", orderId: 1}
]

我想要的是使用 orderId 多次更新所有具有该 ID 的记录

那我该怎么做呢?

我正在尝试这样的事情......但它不起作用,我想它根本没有链接承诺......

'use strict';

module.exports = function(Matchtimelineevents) {
  Matchtimelineevents.reorder = function(items, cb) {
    let count = 0;

    if (typeof items !== 'undefined' && items.constructor === Array) {
      items.forEach(item => {
        Matchtimelineevents.update({'id': item.id, 'orderId': item.orderId}, function() {
          count++;
          console.log('UPDATING: ' + item.id, item.orderId, count);
        });
      });
      // Matchtimelineevents.bulkUpdate(items, null, function() {
      //   console.log(items);
      // });
    }

    cb(null, count);
  };

  Matchtimelineevents.remoteMethod('reorder', {
    accepts: {
      arg: 'items',
      type: 'array',
    },
    returns: {
      arg: 'count',
      type: 'number',
    },
    http: {'verb': 'patch', 'path': '/reorder'},
    description: 'Reorder the items by orderId',
  });
};

最好的方法是什么?

【问题讨论】:

    标签: loopback


    【解决方案1】:

    尝试将 updateAll 与 where 一起使用:

    const updateAllToPromise = item => new Promise((resolve, reject) => {
      Matchtimelineevents.updateAll({
        where: { id: item.id },
      }, {
        orderId: item.orderId,
      }, function (err) {
        if (err) resolve(false);
        else resolve(true);
      });
    });
    
    Matchtimelineevents.reorder = (items, cb) => {
      if (!Array.isArray(items)) cb(new Error('Items not is a Array object'));
      else {
        Promise.all(items.map(item => updateAllToPromise(item)))
          .then(items => cb(null, items.filter(item => item).length))
          .catch(cb)
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-21
      • 2018-04-29
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多