使用mongoose,如果我有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
})
})
});
如果我将Note
架构嵌入到父文档(notesContainerSchema
)中,我是否可以实现相同的功能(过滤,选择,限制,跳过,排序等):
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 :(得分:1)
您可以使用aggregation:
在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);
});