Home > Enterprise >  Mongoose Lookup with foreign key as array
Mongoose Lookup with foreign key as array

Time:04-18

I have a questions collection with _id and name and other fields(..), and a tests collection with _id, name and array of questions.

I'm trying to get all the questions with their fields and adding a field "usedIn" which counts the number of tests that the specific questions is present in.

    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
                },

            ])

This code is giving me this error:

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

What Am I doing wrong ?

CodePudding user response:

You can do it like this:

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

Working example

  • Related