如何在环回中使用过滤器获得订单'2'<'10'?

时间:2019-09-01 12:04:53

标签: loopbackjs loopback

我的数据如['2', '13', '13A', '14-1'],如何使用filter获得正确的订单?谢谢大家。

1 个答案:

答案 0 :(得分:0)

IIUC,您正在将数字(210等)存储为字符串('2''10'等)。

LoopBack依靠数据库执行排序(排序)。

这里有几件事可以尝试:

  1. 修改模型定义以将属性存储为number。 LoopBack很聪明,可以将用户(REST API客户端)提供的字符串值强制转换为数字,然后再存储在数据库中。这将是我的首选解决方案,因为它在您的应用程序中不需要任何复杂的代码,并且可以保持性能。

  2. 取决于所使用的数据库,可能有可能对其进行配置,以将字符串值视为要排序的数字。这不是LoopBack特有的,我真的无法帮助您。

  3. 作为最后的选择,您可以对内存中的记录进行排序,当数据库不支持基于位置的查询时,LoopBack已经在对它们进行分类。这个想法是告诉数据库返回符合filter条件的所有记录,然后在内部应用orderlimitskip和其他选项您的Node.js进程。请注意,这会严重影响性能,并且仅适用于合理大小的数据。

关于第三个选项:明智的实现,您需要在模型类中覆盖find方法。

// common/models/my-model.js
module.exports = function(MyModel) {
  MyModel.on('modelRemoted', () => {
    MyModel._findRaw = MyModel.find;
    MyModel.find = findWithCustomSort;
  });
}

function findWithCustomSort(filter, options, cb) {
  if (!cb) { 
    if (typeof options === 'function') {
      cb = options;
      options = undefined;
    } else if (!options && typeof filter === 'function') {
      cb = filter;
      filter = undefined;
    }
  }

  const dbFilter = {
    where: filter.where, 
    include: filter.include,
    fields: filter.fields,
  };


  if (cb) {
    this._findRaw(dbFilter, options, (err, found) => {
      if (err) return cb(err);
      else cb(null, sortResults(filter, found))
    });
  } else {
    return this._findRaw(dbFilter, options)
      .then(found => sortResults(filter, found));
  }
}

function sortResults(filter, data) {
  // implement your sorting rules, don't forget about "limit", "skip", etc.
}

更新

  

是否可以在自定义方法中使用sql查询?

是的,您可以使用MyModel.dataSource.connector.execute函数执行任何SQL,请参见Executing native SQL。不过有一个问题-这种方法是基于回调的,您不能使用Promise API或async / await。

const idValue = 1;
MyModel.dataSource.connector.execute(
  'SELECT * FROM MyModel WHERE id=?',
  [idValue]
  (err, results) => {
    if (err) console.error('query failed', err);
    else console.log('found data', results);
  });