Search code examples
mongodbmongoosemongodb-queryone-to-manymongoose-populate

In Mongoose I have User and Role schemas that have a one to many relationship. How to query if a particular User has the 'admin' role?


I have two collections in my Mongo DB: users and roles. A user can have many roles. Using Mongoose I want to find out whether a particular user (based on their id) has the admin role. How do I perform that query? In SQL one way of finding out would be to write this query:

SELECT *
FROM Users
INNER JOIN Roles ON Users.id = Roles.userID
WHERE (Users.id = <some user id> AND Roles.name='admin')

But I'm failing to see how the equivalent query is done using Mongoose. Below are my Mongoose schemas:

let RoleSchema = new Schema({
    name: String,
    owner: {
        type: Schema.Types.ObjectId,
        ref: "User"
    }
})
export let Role = mongoose.model("Role", RoleSchema)


let userSchema = new Schema({
    username: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    roles: [
        {
            type: Schema.Types.ObjectId,
            ref: "Role"
        }
    ]
})
export let User = mongoose.model("User", userSchema)

Solution

  • Read - https://mongoosejs.com/docs/populate.html#query-conditions

    User.
      findById(id). // can also use find/findOne depending on your use-case
      populate({
        path: 'roles',
        match: { name: 'admin' }
      }).
      exec();
    

    This will fetch you User details and roles where name is admin.

    You can check the user.roles array count to get the user is having admin role or not.