Mongoose 用户、角色和权限

ffs*_*erv 5 mongoose mongodb node.js express mongoose-schema

我对 NoSQL/Mongo/Mongoose 很陌生,我正在尝试确定设置模式的最佳方法。这是我所拥有的:

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',
      },
    ],
  }
);
Run Code Online (Sandbox Code Playgroud)
const RoleSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
    },
    description: {
      type: String,
    },
    permissions: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Permission',
      },
    ],
  }
);
Run Code Online (Sandbox Code Playgroud)
const PermissionSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
    },
    description: {
      type: String,
    },
  }
);
Run Code Online (Sandbox Code Playgroud)

很简单,用户有角色,角色有权限。

如果我想查找用户及其权限,是否应该通过填充以某种方式完成,即使权限实际上并不是用户架构的直接一部分,还是应该/可能是虚拟

本质上,我想要做的是访问用户的权限,如下所示:

const user = User.findById(id);
console.log(user.permissions);
Run Code Online (Sandbox Code Playgroud)

Mah*_*han 1

如果您想在一个查询中检索用户的权限,您可以使用嵌套填充

这是代码:

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

如果您想了解有关猫鼬种群的更多信息,请参阅