node.js - how to use mongoose pagination with populate and query -
i'm trying use mongoose pagination process advance search pagination.
i have 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 find 24 book page 1 book contains author name 'jean'. following mongoose-paginate module:
book.paginate({}, { page: 1, limit: 24, populate: { path: 'authors', select: 'name', match: { name: 'jean' } }, function (err, books) { res.json(books); });
but result books contains other book authors array empty. cant use books.filter() remove book authors. if that, can't have 24 book per page on result.
what right way that?
instead of populate, suggest use $lookup
in aggregation query.
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} )
Comments
Post a Comment