sails.js中未排序的结果集

时间:2015-09-01 09:32:48

标签: sails.js waterline

是否可以获取查询查询以无序方式返回结果集。我有一个包含以下数据集的表

Id  Country
1   Germany
2   Japan
3   China
4   England
5   USA

触发以下查询

Country.find({id:[1,5,3]}, function (err, result) { 
  res.json(result);
});

我得到了

1  Germany
3  China
5  USA

有没有办法根据id关闭默认排序,并按照预期的顺序设置查询结果?

1  Germany
5  USA
3  China

1 个答案:

答案 0 :(得分:1)

您无法在查找查询中执行此类排序。实际上,您不希望对查询结果进行排序,但是您希望按照数组ID的顺序检索它们。 您可以在此处定义sort()规则。查询语言的var filter = [1,5,3]; Country.find({id:filter}, function (err, result) { sortedResult = _.sortBy(result, function(country) { return _.indexOf(filter, country.id); }); res.json(sortedResult); }); 方法允许您使用列中的值按升序或降序进行排序。看起来这不是你想要做的事情。

一种解决方案是执行 n 查询以独立检索每条记录并将结果放在数组中。它效率不高,需要您编写一些额外的代码来管理从数据库的多个异步调用中的数据。

更好的解决方案是使用lodash。 Lodash带有很多强大的功能来操作集合。完成这项任务是完美的。查看_.sortBy

var filter = [1,5,3];
Country.find({id:filter}, function (err, result) {
  result.sort(function(country_a, country_b) {
    return filter.indexOf(country_a.id) - filter.indexOf(country_b.id);
  })
  res.json(result);
});

默认情况下,lodash is globally available in sails

最后,您可以使用纯JavaScript实现对结果进行排序:

#include "unicode/utypes.h"
#include "unicode/ucnv.h"
#include "unicode/ustring.h"
#include "unicode/uchar.h"
#include "unicode/uloc.h"
#include "unicode/unistr.h"

// RawMessage is received as void *
void ReceiveMessage(  RawMessage )
{
    UChar * UCharUnicodeMessage;
    UCharUnicodeMessage = (UChar*)RawMessage;
    UnicodeString in(UcharUnicodeMessage);
    UErrorCode status = U_ZERO_ERROR;
    char dest[in.length()];
    int ln = in.extract(dest,in.length(), NULL, status);
    cout << endl << "***** Unicode String Received from AEM: " << dest << endl;
    string response;
    in.toUTF8String(response);
    cout << "Result of toUTF8String: " << response;
    // Writes this to our database, the 5 and 19 are debug codes
    LogLongMessage("Test", 5, 19, (char*)response.c_str());
}

我通常首先考虑使用lodash执行此类任务,但纯JavaScript实现在这里很好。无论如何,我认为lodash实现仍然更容易阅读,在许多其他情况下,lodash将给你更多的力量。