Mongodb Recommended List Fields or Multiple Records?

  mongodb, question

Application scenario: background management system, which assigns visible menu permissions to created users. For example, if user A is assigned 10 menus, the user can see the 10 menus in the menu bar after logging in. The menu is now up to 3 levels. According to the current business, the maximum number of menus allocated by a single user is 30.

Now the database uses MongoDB, and there are two storage schemes for menu permissions:

  1. Menu list, that is, each user’s permission list will store a menu list, so that all menus under that user can be seen in a single query of a record.
  2. Menu items are tiled, and each row of records corresponds to a menu of a user, so if the user can see 20 menus, there will be 20 rows of records in the table.

The advantage of Scheme 1 is that it is relatively convenient to store it, and when querying, one record can directly return all menu lists. The advantage of Scheme 2 is that it is very convenient to find out which users are given visibility for a certain menu.

Personally, I prefer Scheme 2, but I am not sure whether it is a universal design method. Do you have any suggestions? Thank you!

Under sql, Scheme 2 is better. Under mongo, Scheme 1 is better.
I don’t know if you have the concept of user rights group in this project.
If there is a permission group, it is the collection of a permission group, and an array of menu items is saved under each permission.
If there is no permission group, a menu array can be saved in each user list or in a separate user permission list according to the scheme 1 you mentioned.
Of course, it may be more appropriate to save the id array of menu items.

The array in mongo can also be indexed, and the query is also very convenient.
In addition, you can also refer to mongo’s own permission system. Its permission settings are also stored in the mongo database, usually the users table under the admin library. If your mongo opens permission management and the name of the permission library is admin, you can view it with the following command:

> use admin
 switched to db admin
 > show users
 {
 "_id" : "admin.admin",
 "user" : "admin",
 "db" : "admin",
 "roles" : [
 {
 "role" : "root",
 "db" : "admin"
 }
 ]
 }
 {
 "_id" : "admin.migration",
 "user" : "migration",
 "db" : "admin",
 "roles" : [
 {
 "role" : "backup",
 "db" : "admin"
 },
 {
 "role" : "read",
 "db" : "local"
 },
 {
 "role" : "read",
 "db" : "some_database"
 }
 ]
 }
 {
 "_id" : "admin.sys",
 "user" : "sys",
 "db" : "admin",
 "roles" : [
 {
 "role" : "__system",
 "db" : "admin"
 }
 ]
 }

The above output is an example. It can be seen that the official storage permission scheme also uses arrays.

Reference:
Mongo Official Documents-User Rights Management
Mongo Official Documents-Array Index