首页 > 解决方案 > 使用 mongoose virtuals 获取文档计数时,无法在排除投影错误中包含字段 studentId

问题描述

我正在使用 mongoose/mongodb 开发一个系统。

所以我有这个架构

const TutorStudentSchema = new mongoose.Schema(
  {
    tutorId: { type: mongoose.Types.ObjectId, ref: 'user', required: true },
    studentId: { type: mongoose.Types.ObjectId, ref: 'user', required: true },
  },
  {
    timestamps: true,
    oObject: { virtuals: true },
    toJSON: { virtuals: true }
  }
)

我创建了一个虚拟

TutorStudentSchema.virtual('count', {
  ref: "practiceSet",
  localField: "studentId",
  foreignField: "studentId",
  match: {submitted: true, reviewed: false},
  justOne: false,
  count: true
})

引用的“practiceSet”架构如下所示:

const TutorStudentSchema = new mongoose.Schema(
  {
    ...
    studentId: { type: mongoose.Types.ObjectId, ref: 'user', required: true },
    ...
  },
  {
    timestamps: true,
    oObject: { virtuals: true },
    toJSON: { virtuals: true }
  }
)

当我用“count:false”填充虚拟计数时,它可以通过获取数组中匹配的所有文档来正常工作,但是当设置“count:true”时,我希望得到匹配文档的计数,但我得到了这个错误:

Cannot do inclusion on field studentId in exclusion projection

我试过同时删除“justOne: false”、“match”和它们。但问题似乎来自将计数设置为真。有什么我在这里想念的吗?

标签: node.jsmongodbmongoose

解决方案


推荐阅读