Mongoose-Paginate - 按人口稠密的土地排序

时间:2016-12-15 21:32:17

标签: javascript node.js mongodb mongoose

我使用mongoose-paginate来获取按引用填充的字段排序的记录列表。



// models

const Company = new Schema({
  name: String,
  type: String
});

const report = new Schema({
  _company: { 
    type: String, 
    ref: 'Company' 
  },
  name: String
});

let options = {
  offset: 0,
  limit:10,
  populate: '_company',
  select: 'type _company',
  sort: { '_company.name': 1 },
  lean: true
};

// paginate.
report.paginate({},options, (err, results) =>  {
  if(err) {
    console.log(err);
  }
  
  res.jsonp({
    data: results
  });
})




有没有办法按字段_company.name排序,这是一个填充的字段。

在下面添加了示例代码。

感谢。

1 个答案:

答案 0 :(得分:1)

  

Mongo没有加入。对填充文档进行排序的唯一方法就是这样做   在收到所有结果后手动完成。

或者对于您在问题中定义的架构,您应该在comany架构中报告子文档。像这样。

const reportSchema = new Schema({
  name: String
});


const companySchema = new Schema({
  name: String,
  type: String,
    reports: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Report'
    }],

});

// we need to create a model to use it
var Company = mongoose.model('Company', companySchema);
var Report = mongoose.model('Report', reportSchema);

并且用户聚合以对报告进行排序和展开以列出所有报告。

Comapnay.aggregate( [ { 
$match: { <whatever query you want to user> } },
{ $sort : { name : 1 } }
{ $unwind : "$reports" } ] )
相关问题