使用猫鼬,如果我有一个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);
请参阅['$切片'](https://docs.mongodb.com/manual/reference/operator/projection/slice/)。从MongoDB的开始就已经出现了这个特定的目的。 –
我了解'$ slice'如何用于'skip'和'limit'。我不知道我怎么也可以'筛选','选择'和'排序'数据呢? – CSharp
如果你真的**需要**所有这些操作,那么保存为单独的集合可能会更好。你可以交替使用['$ lookup']](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/)而不是'.populate()'来执行“加入”在你需要数据的时候在服务器上。但是对于嵌入,我们可以用数组,“$ filter”等来做“最”的事情。然而像'$ sort'(动态的那样)仍然需要'$ unwind'。 '$ unwind'意味着在所有情况下的表现痛苦。 –