在Mongoose中使用$lookup检索引用字段的最佳方式



我有两个模型BookAuthor,Book有Author的参考,假设Author被删除,那么我只想检索那些有作者的书:

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游乐场,看看它在上的工作

最新更新