2017-06-16 44 views
1

使用猫鼬,如果我有一个Note模式,我可以检索排序并分页使用的find功能查询选项,像这样的结果......检索嵌入文档分页结果中猫鼬

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)内Note模式,像这样:

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); 
+0

请参阅['$切片'](https://docs.mongodb.com/manual/reference/operator/projection/slice/)。从MongoDB的开始就已经出现了这个特定的目的。 –

+0

我了解'$ slice'如何用于'skip'和'limit'。我不知道我怎么也可以'筛选','选择'和'排序'数据呢? – CSharp

+1

如果你真的**需要**所有这些操作,那么保存为单独的集合可能会更好。你可以交替使用['$ lookup']](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/)而不是'.populate()'来执行“加入”在你需要数据的时候在服务器上。但是对于嵌入,我们可以用数组,“$ filter”等来做“最”的事情。然而像'$ sort'(动态的那样)仍然需要'$ unwind'。 '$ unwind'意味着在所有情况下的表现痛苦。 –

回答

1

您可以使用aggregation具有:

否deJS,与猫鼬:

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); 
}); 
+2

显然你需要阅读['$ slice'](https://docs.mongodb.com/manual/reference/operator/projection/slice/)文档。请不要在简单的内置操作员完成工作时提出复杂的汇总语句。 –

+0

感谢您的回复。我在调用'$ replaceRoot'时返回undefined。我正在使用mlab提供的数据库,不确定它是否是版本问题。没有使用'$ replaceRoot'获得相同结果的更长途径吗? – CSharp

+1

查看更新的帖子,'$ replaceRoot'实际上并不需要,我使用@NewLunn建议的'$ slice' –