我有两个模型 Book 和 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 }
}
}
]);
最佳答案
您已正确完成所有操作,但您不需要在 aggregation
管道的第二阶段使用 $match
。 $unwind
会自动移除bookAuthor
数组为空的文档,所以如果没有author
,会在$unwind之后移除
阶段。
试试这个:
const books = await Book.aggregate([
{ $lookup: {
from: 'authors',
localField: 'author',
foreignField: '_id',
as: 'bookAuthor'
}
},
{ $unwind: '$bookAuthor' },
{ $project: {
name: 1,
bookAuthor: { name: 1 }
}
}
]);
看看这个Mongo Playground看到它工作
关于mongodb - 在 Mongoose 中使用 $lookup 检索引用字段的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64982331/