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

이것은 몽구스 - 페이지 매김 모듈을 사용하지 않습니다. 모듈에 대한 답변을 표시 할 수 있습니까? – zubair1024