DEV Community

Manda Putra
Manda Putra

Posted on

How do you design your noSQL database for RBAC system?

RBAC is like an user role system, in word-press or any CMS and dev.to have it too. But how do you design your database in mongodb/nosql? since the bad and good of nosql it is fluidness and dont care much about our database design (IMO) how would you make it on mongodb/noSQL? using collection as a pivot? same as SQL database?

Here is the things.

  1. User had a role
  2. User had a menu
  3. Some user just can see the menu, but cant edit/update the menu
  4. Some user fully get all access to the menu

EDIT:

Here comes my schema approach so far :

menus.model.js

module.exports = function (app) {
  const mongooseClient = app.get('mongooseClient');
  const { Schema } = mongooseClient;
  const menus = new Schema({
    name: { type: String, required: true },
    slug: { type: String, required: true },
    menu_roles: [{
      roles_id: { type: Schema.Types.ObjectId, ref : 'Roles' },
      roles_name: { type:  String },
      create: { type: Boolean },
      delete: { type: Boolean },
      update: { type: Boolean },
      read: { type: Boolean },
    }]
  }, {
    timestamps: true
  });

  return mongooseClient.model('menus', menus);
};

Enter fullscreen mode Exit fullscreen mode

roles.models.js

module.exports = function (app) {
  const mongooseClient = app.get('mongooseClient');
  const { Schema } = mongooseClient;
  const roles = new Schema({
    name: { type: String, required: true },
    slug: { type: String, required: true },
  }, {
    timestamps: true
  });

  return mongooseClient.model('roles', roles);
};

Enter fullscreen mode Exit fullscreen mode

users.models.js

module.exports = function (app) {
  const mongooseClient = app.get('mongooseClient');
  const { Schema } = mongooseClient
  const users = new mongooseClient.Schema({

    email: {type: String, unique: true, lowercase: true},
    password: { type: String },
    first_name: { type: String },
    last_name: { type: String },
    roles: { type: Schema.Types.ObjectId, ref : 'Roles' },

  }, {
    timestamps: true
  });

  return mongooseClient.model('users', users);
};

Enter fullscreen mode Exit fullscreen mode

Still on work, feedback are pretty welcome thanks!

Discussion (2)

Collapse
guillerbr profile image
Guiller

Use npm module access control,RBAC module functions for no Node.

Collapse
mandaputtra profile image
Manda Putra Author

Hi, what do you mean? I just made my own middleware to every request so they check user permission on every request.