我在尝试用嵌套引用填充文档时迷失了
首先我有Group文档,嵌套子文档Group>角色>权限 使用以下模型定义:
group.model.js
const PermissionSchema = new Schema({
resourceName: { type: String, trim: true },
authorizedActions: [ { type: String, trim: true }]},
{ _id: false }
);
const RoleSchema = new Schema({
name: { type: String },
permissions: [PermissionSchema]
});
/**
* Group Schema
*/
const GroupSchema = new Schema({
name: { type: String, unique: true, required: true },
roles: [RoleSchema]
});
然后我有一个用户文档,每个用户将有多个组/角色参考
用户/ model.js
const RoleSchema = new mongoose.Schema({ roleId: { type: ObjectId } }, { _id: false })
const GroupSchema = new mongoose.Schema({
groupId: { type: ObjectId },
roles: [RoleSchema] }, { _id: false })
const UserSchema = new mongoose.Schema({
username: { type: String, unique: true, required: true },
groups: [GroupSchema],
});
使用User.get(id)加载用户时,我想用Groups / Roles文档值填充用户引用。
UserSchema.statics = {
/**
* Get user
* @param {ObjectId} id - The objectId of user.
* @returns {Promise<User, APIError>}
*/
get(id) {
return this.findById(id)
.populate('WHAT SHOULD I WRITE HERE ?)
.exec()
.then((user) => {
if (user) { return user; }
const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
return Promise.reject(err);
});
},
1-我应该改变模特吗? 2-我应该如何编写populate()路径?
感谢您的反馈