Sunday, 29 November 2020

Mongoose: How to get documents that their subdocument includes a value ( Many to one relationship )

I have a situation that i need to filter users based on their Profession, here is how the User Schema is defined:

const userSchema = new mongoose.Schema(
  {
    userData: {
      professions: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Profession'
        }
      ]
    }
  }
)

and here we have for Professions schema:

const ProfessionSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
    }
  }
)

How can I get a list of users that have a profession with an id of 5f8ea4396586f1168ab3a298 for example?

I tried

User.find({
    "userData.professions": { $elemMatch: $in: ["5f8ea4396586f1168ab3a298"] }
})

But seems like this is the opposite of what I'm trying to do. I need to get a result like this when I filter results based on 5f8ea4396586f1168ab3a298 as id of profession

[
    {
        "name": "John Doe",
        "userData": {
            "professions": ["5f8ea4396586f1168ab3a298", "5f8ea4226586f1168ab3a296"]
        }
    },
    {
        "name": "John Smith",
        "userData": {
            "professions": ["5f8ea4396586f1168ab3a298",]
        }
    },
    {
        "name": "Elon Musk",
        "userData": {
            "professions": ["5f8ea4466586f1168ab3a29a", "5f8ea4396586f1168ab3a298", "5f8ea4146586f1168ab3a295"]
        }
    }
]


from Mongoose: How to get documents that their subdocument includes a value ( Many to one relationship )

No comments:

Post a Comment