【发布时间】:2020-11-24 16:44:42
【问题描述】:
我有两个模型Book和Author,Book有Author的引用,假设一个Author被删除了,那么我只想检索那些有作者的Book:
BookSchema 包含这些字段
name: String,
author: {
type: Schema.Types.ObjectId,
ref: 'Author',
required: [true, 'A book must have an author']
}
AuthorSchema 包含这些字段
name: String
我必须使用 $lookup 运算符来完成。我能够得到想要的结果,但我不知道这是否是一个好方法。这是我的解决方案:
const books = await Book.aggregate([
{ $lookup: {
from: 'authors',
localField: 'author',
foreignField: '_id',
as: 'bookAuthor'
}
},
{ $match: { bookAuthor: { $not: { $size: 0 } } } },
{ $unwind: '$bookAuthor' },
{ $project: {
name: 1,
bookAuthor: { name: 1 }
}
}
]);
【问题讨论】:
标签: mongodb mongoose aggregation-framework