2016-12-15 99 views
0

我正在使用mongoose-paginate來獲取按照從參考填充的字段排序的記錄列表。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

您不能在填充字段上執行查詢,因爲填充字符在查詢後發生。人口是一種貓鼬特徵,而不是mongoDB。解決方案可以是2個查詢。 – alfredopacino

回答

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" } ])