【问题标题】:Mongoose User, Roles & PermissionsMongoose 用户、角色和权限
【发布时间】:2020-10-20 12:46:17
【问题描述】:

我对 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',
      },
    ],
  }
);
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,
    },
  }
);

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

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

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

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

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-schema


    【解决方案1】:

    如果您想在一个查询中检索用户的权限,您可以使用nested population

    代码如下:

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

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

    【讨论】:

    • 感谢您的回答,我可以确认此方法确实填充了权限。
    猜你喜欢
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2015-11-26
    • 2018-11-18
    • 2015-05-28
    • 2017-10-13
    • 2019-06-12
    相关资源
    最近更新 更多