[英]how to use mongoose pagination with populate and query
I'm trying use mongoose pagination to process advance search with pagination. 我正在尝试使用猫鼬分页来处理带有分页的高级搜索。
I have the following schemas: 我有以下架构:
const authorSchema = Schema({
_id: Schema.Types.ObjectId,
name: {type: String, unique: true},
});
const Author = mongoose.model('author', authorSchema, 'author');
const bookSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
authors:[{type: Schema.Types.ObjectId, ref: 'author'}]
});
const Book= mongoose.model('book', bookSchema , 'book');
I want to find 24 book for page 1 with any book contains author name 'jean'. 我想为第1页找到24本书,其中任何一本书包含作者姓名'jean'。 I do the following with mongoose-paginate module:
我对mongoose-paginate模块执行以下操作:
Book.paginate({}, {
page: 1,
limit: 24,
populate: {
path: 'authors',
select: 'name',
match: {
name: 'jean'
}
}, function (err, books) {
res.json(books);
});
But the result books contains other book with authors array empty. 但是结果书包含其他作者列表为空的书。 I cant use books.filter() to remove book with authors.
我不能使用books.filter()与作者删除书。 But if i do that, i can't have 24 book per page on result.
但是,如果我这样做的话,我将无法获得每页24本书的结果。
What is the right way to do that? 什么是正确的方法?
Instead of populate, I suggest to use $lookup
in aggregation query. 建议不要在聚合查询中使用
$lookup
来填充。
db.book.aggregate(
{$unwind:'$authors'},
{$lookup:{
from: 'author',
localField: 'authors',
foreignField: '_id',
as: 'authors'
}},
{$unwind: '$authors'},
{$match: {'authors.name':'Jean'}},
{$group: {_id: '$_id', authors: {$push: '$authors'}}},
{$limit: 24}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.