首页 文章

Mongoose按填充字段排序

提问于
浏览
2

好吧,我有以下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进行了查询并找到用户所做的所有FollowActions,然后填充品牌字段 .

所以问题是我无法对品牌名称进行排序,我知道这样做的唯一方法是返回所有文档并从nodejs app中对它们进行排序 . 谁知道我该怎么做?或者我应该改变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);
      });

2 回答

  • 2

    从这个简单的例子中获取想法

    Post.find({'_id': userId})
               .limit(10)
               .skip(0)
               .sort({'created_at':-1}) // this is used to sort
               .exec(function(error, result){
                if(!error){
                  // console.log(result);
                  res.send({data:result});
                } else{
                  console.log(error);
                }
            });
    
  • 1

    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'
      },
      // ...
    });
    

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

    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.
       });
    

相关问题