2017-09-11 3 views
2

私はページングを使って事前検索を処理するためにモンゴーズのページネーションを使っています。モンゴーズのページネーションの使用方法と照会方法

私は、次のスキーマを持っている:

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'); 

私は1ページのための24本を探したいどんな本では、著者名「ジーンズ」が含まれています。

Book.paginate({}, { 
    page: 1, 
    limit: 24, 
    populate: { 
    path: 'authors', 
    select: 'name', 
    match: { 
     name: 'jean' 
    } 
    }, function (err, books) { 
     res.json(books); 
    }); 

しかし、結果の本は空の著者配列と他のブックが含まれています。私はmongoose-paginateモジュールで次のようにします。私はbooks.filter()を使って著者と一緒に本を取り除きます。しかし、もし私がそれを行うと、私は24ページの本の結果を得ることはできません。

これを行う正しい方法は何ですか?

答えて

0

集計の代わりに、$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} 
) 
+1

これはmongoose-paginateモジュールを使用しないため、モジュールで回答を表示できますか。 – zubair1024

関連する問題