Search code examples
javascriptnode.jsmongodbexpressmongoose

Express mongoose filter array of ids


I have a user schema were it has a role ref which is an array of ids and i want to filter user with role id.

const users = await User.find(
  { roles: { $in: [params.role] } },
  "-password"
)
  .populate({
    path: "roles",
  });

This is my user schema.

const userSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      required: true,
    },
    password: { type: String, required: true },
    contact: { type: mongoose.Schema.Types.ObjectId, ref: "Contact" },
    roles: [{ type: mongoose.Schema.Types.ObjectId, ref: "Role" }],
  },
  {
    timestamps: true,
  }
);

Here params.role is single role id and i getting empty user result here.


Solution

  • If params.role is a single value then you don't need $in. Since User.roles is an array of type ObjectId mongoose should cast the search string to an ObjectId for you so you can just search in the normal way but make sure there is a value in params.role and it's not actually req.params.role that you mean:

    console.log('params.role=', params.role);
    const users = await User.find({ roles: params.role}, "-password").populate({
        path: "roles",
    });