在Mongoose中检索embedded文档的分页结果

使用mongoose,如果我有一个Note模型,我可以检索分页和sorting结果使用查询选项的findfunction,如此…

  Note.find({ creator: creatorId}) .select('text') .limit(perPage) .skip(perPage * page) .sort({ name: 'asc' }) .exec(function(err, notes) { Note.count().exec(function(err, count) { res.render('notes', { notes: notes, page: page, pages: count / perPage }) }) }); 

如果我在父文档( notesContainerSchema )中embeddedNote模式,可以实现相同的function(筛选,select,限制,跳过,sorting等):

 var noteSchema = new Schema({ creator: { type: String }, text: { type: String } }); var notesContainerSchema = new Schema({ key: { type: String, unique: true }, notes: [ noteSchema ] // note schema is now an array of embedded docs }); var NotesContainer = db.model('notesContainer', notesContainerSchema); 

您可以使用以下内容的聚合 :

  • 一个$ project阶段,用$ creatorId 过滤 notes数组, $和$ slice结果
  • $ unwind阶段来展开notes数组
  • $按名称sorting
  • $project只能selecttext字段

在nodeJS中,用mongoose:

 NotesContainer.aggregate([{ $project: { notes: { $slice: [{ "$filter": { "input": "$notes", "as": "item", "cond": { "$eq": ["$$item.creator", creatorId] } } }, (perPage * page), perPage] } } }, { $unwind: "$notes" }, { $sort: { "notes.name": 1 } }, { $project: { "text": "$notes.text", "_id": 0 } }]).exec(function(err, notes) { console.log(notes); });