node.js - Mongoose 按填充字段排序

标签 node.js mongodb sorting mongoose

好吧,我有以下 shemas:


    var BrandSchema = new Schema({
      name: {
        type: String,
        required: true,
        index: {
          unique: true
        },
        lowercase: true
      },
      logo: {
        type: ObjectId,
        ref: 'Image'
      }
    });

    var FollowActionSchema = new Schema({
      'actionDate': {
        type: Date,
        'default': Date.now
      },
      'brand': {
        type: ObjectId,
        ref: 'Brand'
      },
      'performer': {
        type: ObjectId,
        ref: 'User'
      },
      'type': String // followUser, folloBrand, followMerchant
    });

我想要的是让用户关注品牌,按品牌名称排序,为此我查询了 FollowAction 并找到用户执行的所有 FollowAction,然后填充品牌字段。

所以问题是我无法对品牌名称的查询进行排序,我知道的唯一方法是返回所有文档并从 nodejs 应用程序对它们进行排序。任何人都知道我该怎么做?或者我是否应该更改 shema 结构??

我做的查询是:


       async.waterfall([
        function findActions(next) {
          var options = {
            query: {
              performer: userId,
              $or: [{
                type: 'followBrand'
              }, {
                type: 'followMerchant'
              }]

            },
            projection: {
              actionDate: 1,
              brand: 1,
              merchant: 1,
              type: 1
            },
            sort: '-actionDate',
            pagination: pagination
          };
          utils.limitQuery('FollowAction', options, next);
        },
        function inflate(actions, next) {
          total = actions.count;
          var options = {
            projection: {
              name: 1,
              _id: 1,
              username: 1
            }
          };
          async.eachSeries(actions.result, function(action, done) {
            async.waterfall([
              function inflateAction(done) {
                action.inflate(options, done);
              },
              function addToArray(item, done) {
                trusted.push({
                  _id: item._id,
                  name: utils.capitalize(item.name || item.username),
                  type: item.name ? 'brand' : 'merchant'
                });
                return done(null, item);
              }
            ], done);
          }, next);
        }
      ], function(err) {
        callback(err, trusted, total);
      });

最佳答案

Mongoose API 似乎确实支持对填充字段进行排序,但有一个错误完全破坏了它:https://github.com/Automattic/mongoose/issues/2202 .您得到了一个结果,但它显然是错误的。

对于少量数据,可以使用 Javascript 对结果数组进行排序 Array.prototype.sort() .请记住,这会直接修改已排序的数组。

在这种情况下,我所做的是将排序键属性添加到您要排序的模型的架构中。对于您的示例,您可以这样做:

var FollowActionSchema = new Schema({
  // ...
  'brandSortKey': { type: String },
  'brand': {
    type: ObjectId,
    ref: 'Brand'
  },
  // ...
});

这并不完美,因为您必须自己使用正确的 key 显式设置此属性:

var FollowAction = Model('FollowAction', FollowActionSchema);

var aBrand = // some brand object

var f = new FollowAction({
   brand: aBrand._id,
   brandSortKey: aBrand.name
   // other properties
}); 

但是,您可以直接通过 Mongoose API(或 MongoDB)进行排序:

FollowAction.find({})
   .sort({ brandSortKey:1 })
   .exec(function (err, sortedResults) {
       // do something with sorted results.
   });

关于node.js - Mongoose 按填充字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31180455/

相关文章:

node.js - nodejs multer文件上传,路径包含双斜杠

node.js - 在 Node Js 中处理基于 token 的授权

python - 检索 GridFS 中要从 Flask 发送的文件?

node.js - 使用 Mongoose 更新请求正文中的嵌入文档

java - 用于对 ArrayList 进行排序的 Java 内联比较器的问题

javascript - 统计来自 Discord 服务器的消息 - Discord.js

mongodb - 连接字符串 'mongodb//localhost' 无效

java - 为什么这种快速排序分区方法是错误的?

excel - 在 Excel 中按字母顺序排序的顺序公式

javascript - Electron - 如何添加外部文件?