以外键作为数组的猫鼬查找

Mongoose Lookup with foreign key as array

我有一个 questions 集合,其中包含 _idname 以及其他字段(.. ),以及一个 tests 集合,其中包含 _idnamearray of questions.

我正在尝试获取所有问题及其字段并添加一个字段“usedIn”,该字段计算特定问题出现的测试数量。

    questions = await Question.aggregate([
                /*{
                    "$match": {
                        params
                    }
                },*/
                {

                    "$lookup": {
                        "from": "tests",
                        "let": {"questionId": "$_id"},
                        pipeline: [
                            {
                                "$match": {
                                    "$expr": {
                                        "$in": ["$$questionId", "$questions"],
                                    },
                                },
                            },
                        ],
                        as: "tests"
                    }
                },

                {
                    "$addFields": {
                        "usedIn": {
                            "$size": "tests"
                        }
                    }
                },
                {
                    "$project": fieldsObject
                },

            ])

这段代码给我这个错误:

Error: Failed to optimize pipeline :: caused by :: The argument to $size must be an array, but was of type: string

我做错了什么?

你可以这样做:

db.questions.aggregate([
  {
    "$lookup": {
      "from": "tests",
      "localField": "_id",
      "foreignField": "questions",
      "as": "usedIn"
    }
  },
  {
    "$project": {
      "usedIn": {
        "$size": "$usedIn"
      },
      "name": 1
    }
  }
])

Working example