【问题标题】:Best way to retrieve a reference field using $lookup in Mongoose?在 Mongoose 中使用 $lookup 检索参考字段的最佳方法?
【发布时间】:2020-11-24 16:44:42
【问题描述】:

我有两个模型BookAuthor,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


    【解决方案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 看看它的工作原理

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 2016-12-11
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多