node.js - Mongoose 对填充的子文档进行排序

标签 node.js mongodb sorting mongoose-populate

我有一个 Mongoose 模型,其中有需要填充的路径:

var adsSchema = new Schema({                                                                   
    price:      { type: Number, min: 0, required: true }, 
    author:     { type: ObjectId, ref: 'Users', required: true }, 
    title:      { type: String, required: true }, 
    date:       { type: Date, default: Date.now }, 
    offers:     [{                                
        price:      { type: Number, required: true },                                          
        date:       { type: Date, default: Date.now },                                         
        offerBy:    { type: ObjectId, ref: 'Users', required: true }                           
    }],                                                                                        
    category:   { type: ObjectId },                                                            
    images:     [{                                                                             
        type: ObjectId,                                                                        
        ref: 'Images'                                                                          
    }],                                                                                        
    videos:     [String]                                                                       
});

在某些 GET 请求中,我需要填充许多字段,正如我所说,特别是按“价格”升序排序的报价。

正如 Mongoose 的文档所示( http://mongoosejs.com/docs/api.html#query_Query-populate ),您可以按子路径排序。

我的问题是事实并非如此。

我的代码正在执行此操作:

Ads.findOne({ _id: adId })
  .populate({ path: 'author', select: 'firstName lastName' })
  .populate('images')
  .populate({ path: 'offers', options: { sort: { 'price': -1 } })
  .populate({ path: 'category', select: 'name' })
  .exec(function (err, ad) {
     if (err)
       deferred.reject({ status: 500, message: 'Database error.' });
     else if (!ad)
       deferred.reject({ status: 500, message: 'The ad doesn\'t exist!.' });
     else {
                deferred.resolve(ad.toJSON());
     }
})

我已阅读了此处或 Mongoose 邮件列表中给出的尽可能多的问题/答案:

我知道不可能从子文档结果中对文档结果进行排序,好的。但我只想对那个子文档进行排序,而且只对这个子文档进行排序。这里的一些回复似乎说这是可能的:

我有两个问题:

  • 是否可以(如 Mongoose 文档的编写)在填充过程中对子文档进行排序?
  • 这是否与我没有将 ObjectId 链接到其他架构有关?

感谢您的回答;)

最佳答案

就我个人而言,我不会尽可能使用“填充”。过去我经历过很多麻烦。所以,我不知道如何在填充时排序。

您可以使用 $lookup 方法进行聚合,而不是使用 populate,并且可以轻松对任何字段进行排序。这与“人口”几乎相同。

Ads.aggregate([
        {
          $lookup: {
            from: 'Users',
            localField: 'author',
            foreignField: '_id',
            as: 'authorName'
          }
        },
        {
          $lookup: {
            from: 'Images',
            localField: 'images',
            foreignField: '_id',
            as: 'image'
          }
        },
        {
          $lookup: {
            from: 'categories',
            localField: 'category',
            foreignField: '_id',
            as: 'category'
          }
        },
        {
          $project: {
            'authorName.firstName': 1,
            'image.imagePath': 1,
            'category.categoryName': 1,
            '_id': 0
          }
        },
        {
          $sort : { 'authorName.firstName' : -1} 
        }

      ]).exec(function(err, adss) {

      });

我没有正确检查所有字段。请将这种方式应用到您的模型中,希望这能给您一些想法。祝你好运

关于node.js - Mongoose 对填充的子文档进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36824890/

相关文章:

node.js - node_modules 从 "main"(package.json) 中指定的目录导入?

javascript - 不要从 js 对象发送数据

mongodb - ObjectID 和字符串版本之间的唯一区别是它更小?

javascript - Lodash - 将对象移动到数组中的第一位而不是按另一个属性排序

c++ - 如何将字符串的多重映射排序为值

javascript - Stripe Checkout undefined reference 错误

javascript - 类型错误 : Cannot set property 'xxx' of undefined

javascript - 添加更多路由后,express.js 在每个页面上都会出现错误 500

c# - 使用 C# 驱动程序将新字段插入 MongoDB 中的现有集合(许多文档)

javascript - 从数组数组中对日期 mm/dd/yyyy 字段进行排序