【问题标题】:Mongoose aggregate lookup returns empty arrayMongoose 聚合查找返回空数组
【发布时间】:2021-06-28 14:52:57
【问题描述】:

我一直在寻找我遇到的问题我发现了很多与我的问题相关的问题,但它对我不起作用。我不知道我错过了什么!

在我的架构中,我是这样做的:

 student: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Student',
      required: true,
    },

按照我的逻辑是这样的:

 const agg = await MarksModel.aggregate([
      {
        $match: {
          student: studentObj._id,
          course: courseObj._id,
        },
      },
      {
        $group: {
          _id: {
            subject: '$subject',
            course: '$course',
            student: '$student',
            semester: '$semester',
          },
          totalTheoryMarks: { $sum: '$theoryMarks' },
          totalPracticalMarks: { $sum: '$practicalMarks' },
        },
      },
      {
        $lookup: {
          from: 'Student', // I tried students, student, Students & Student.
          localField: 'student',
          foreignField: '_id',
          as: 'student',
        },
      },
    ])

一切都很好,但我总是返回一些这样的输出:

 [
   {
     _id: {
       subject: 60c700aaf6deb877000028c4,
       course: 60b8fe0fccbe980f70e6542d,
       student: 60c1f2a7f12ac51544035a12,
       semester: 3
     },
     totalTheoryMarks: 30,
     totalPracticalMarks: 30,
     student: [] // This is the issue I have
   }
 ] 

【问题讨论】:

  • localField: 'student' => localField: '_id.student'?
  • 这一行是什么意思?

标签: node.js mongodb mongoose


【解决方案1】:

我通过滑动 $lookup 和 $group 解决了我的问题。 $group 使用 $lookup 中从上到下的引用数组。

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 2020-10-10
    • 2017-11-13
    • 2016-11-16
    • 2021-03-30
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2018-06-12
    相关资源
    最近更新 更多