MongoDB: Cannot use complex condition in subdocument

Issue

This Content is from Stack Overflow. Question asked by VladRia

I would like to count all rooms for the particular user with particular roles.

Here is my schema:

const RoomSchema = new Schema({
  ...
  moderator: String,

  // Subdocument with two fields *email* and *role*
  participants: {
    type: [{
      _id: false,
      email: {
        type: String,
        index: {
          unique: true,
        },
      },
      role: String,
    }],
    default: [],
  },
  ...
})

Here is the query:

  let userEmail = "xxx"

  const result = await RoomModel
    .count({
      $or: [
        { moderator: userEmail },
        {
          participants: {
            email: userEmail,
            // role: "reader", works fine
            // role: { $in: ["reader"] }, ERROR
          }
        },
      ]
    })
    .exec()

Here is the error:

CastError: Cast to string failed for value "{ '$in': [ 'reader' ] }" (type Object) at path "role" for model "Room"

Thank you in advance.



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?