帆+蒙戈+水线。按填充集合中的计数文档排序

时间:2015-07-22 08:00:15

标签: node.js mongodb sorting sails.js waterline

我有两个型号 - 用户和标签。用户模型的一部分

module.exports = {
    attributes: {

        tags: {
            collection: "tag",
            via: "users"
        }
}};

标签模型看起来像

module.exports = {
    attributes: {
        name: {
            type: 'string',
            required: true
        },
        users: {
            collection: "user",
            via: "tags"
        },
}};

我需要按" users.length"对标签进行排序。 (每个标签可以有不同数量的用户)。我试过这个

Tag.find().populate('users').sort('users.length DESC').exec(function(err, tags){});

我也试过这样的事情

Tag.native(function (err, collection) {

        if (err) return res.serverError(err);

        collection.aggregate(
            [
                { $sort : { users : -1 } }
            ], function (err, results) {                      
        });

    });

但我失败了。文档未按正确顺序排序。你可以帮我按你想要的文件分类吗?我也是Sails和Mongo的新人。我不知道我怎么能这样做。

P.S。

我使用sails-mongo适配器版本0.11.2

1 个答案:

答案 0 :(得分:2)

不幸的是,到目前为止还没有办法做到这一点。

我建议在$ perl -e '/{/' # Beginning of pattern, no warning $ perl -e '/.{/' # Doesn't follow alpha, no warning $ perl -e '/x{3}/' # Valid quantifier, no warning $ perl -e '/\x{/' # Part of special escape sequence \x{}, different warning Missing right brace on \x{} in regex; marked by <-- HERE in m/\x{ <-- HERE / at -e line 1. $ perl -e '/x{/' # Follows alpha, isn't a quantifier or special escape, warns Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/x{ <-- HERE / at -e line 1. 模型中维护count字段,并在每次Tag添加或删除User时更新该字段。然后像使用Tag作为排序键一样运行常规查询。如果您只需要count信息(而不是Tag),这样做还可以让您更快地查询,因为您可以跳过内部引用其他集合的users调用。

相关问题