我对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,
},
}
);
简单明了,用户具有角色,角色具有权限。
如果我想查找用户及其权限,即使权限实际上不是用户架构的直接组成部分,也应该通过填充完成,还是应该/可以虚拟?
本质上,我想做的就是访问用户的权限,如下所示:
const user = User.findById(id);
console.log(user.permissions);
答案 0 :(得分:0)
如果您想在一个查询中检索用户的权限,则可以使用嵌套填充。
代码如下:
User.findById(id)
.populate({
path: 'roles',
populate: [{
path: 'permissions',
model: 'Permission'
}]
}).exec();
如果您想了解有关猫鼬种群的更多信息,请参见this