Search code examples
node.jsmongodbexpressmongoosemongoose-schema

Mongoose User, Roles & Permissions


I'm pretty new to NoSQL/Mongo/Mongoose and I'm trying to determine the best way of setting up the schemas. Here's what I have:

const UserSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true,
      minlength: 6,
      select: false,
    },
    roles: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Role',
      },
    ],
  }
);
const RoleSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
    },
    description: {
      type: String,
    },
    permissions: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Permission',
      },
    ],
  }
);
const PermissionSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
    },
    description: {
      type: String,
    },
  }
);

Straightforward enough, the User has Roles and Roles have Permissions.

If I wanted to find a user and their permissions, should this be done via populate somehow even though the permissions aren't actually directly part of the User schema, or should/could this be a virtual?

Essentially, what I want to be able to do is access the user's permissions something like this:

const user = User.findById(id);
console.log(user.permissions);

Solution

  • If you want to retrieve permissions of a user in one query you can use nested population.

    Here is the code:

    User.findById(id)
        .populate({
            path: 'roles',
            populate: [{
              path: 'permissions',
              model: 'Permission'
        }]
    }).exec();
    

    If you want to read more about mongoose population see this