多对多关系-在查询-Keytonejs中填充相关数据
many-to-many relationship - populating related data in query - Keystonejs
我在这里处理一个keystonejs项目,遇到了两个模型之间关系的问题。
我有以下两种型号:
用户型号:
User.add({
name: { type: Types.Name, required: true, index: true },
email: { type: Types.Email, initial: true, required: true, index: true },
number: { type: Types.Number, index: true },
password: { type: Types.Password, initial: true, required: true }
}, 'Permissions', {
isAdmin: { type: Boolean, label: 'Can access Keystone', index: true },
}, 'Groups', {
groups: {type: Types.Relationship, ref: 'Group', many: true }
});
我有一个团体模型
Group.add({
name: { type: String, required: true, index: true },
description: { type: String, initial: true, required: true, index: true}
});
我有一个聚合函数,它基本上拉取所有有用户的组
User.model.aggregate({$group:{'_id':'$groups'}}).exec(function(err,data){
console.log(data);
});
我的问题是,上面的聚合只显示了我的组的_id值,而不是它们的名称。
如何填充并在前端显示名称?显然,id在后端是必要的,但对前端用户来说是不起作用的。
感谢
你可以很容易地创建你想要的东西,所以不要气馁。您只需要了解mongoose中的'.populate()'函数。请参阅下面的示例。
用户模型(稍微整理一下-我删除了(奇怪的?)嵌套)
User.add({
name: { type: Types.Name, required: true, index: true },
email: { type: Types.Email, initial: true, required: true, index: true},
number: { type: Types.Number, index: true },
password: { type: Types.Password, initial: true, required: true },
isAdmin: { type: Boolean, label: 'Can access Keystone', index: true },
groups: {type: Types.Relationship, ref: 'Group', many: true }
});
组模型--注意我在底部附近添加的Group.rerelation({})选项,以方便管理(显示在后端引用该组的用户)
Group.add({
name: { type: String, required: true, index: true },
description: { type: String, initial: true, required: true, index: true}
});
Group.relationship({ ref: 'User', path: 'users', refPath:'Groups'});
控制器获取用户列表及其所有相应的组信息
view.on('init', function(next) {
keystone.list('User').model.find()
.populate('groups')
.exec(function(err, users) {
if(err) {
console.log(err);
return next(err);
} else {
locals.data.users = users;
next(err);
}
});
});
控制器让特定组中的用户显示在前端(您首先需要组ID)
view.on('init', function(next) {
keystone.list('User').model.find()
.where('Groups').in([array, of, group, ids])
.populate('groups')
.exec(function(err, users) {
if(err) {
console.log(err);
return next(err);
} else {
locals.data.users = users;
next(err);
}
});
});
locals.data.user在每种情况下都会这样返回:
[
{
_id: '',
name: '',
...
groups: [
{
_id: '',
name: ''
...
}
]
}
]
相关文章:
- 如何在Highchart中动态填充数据
- 使用jquery在选择框中的选项中填充数据
- 使用jquery、javascript重新填充数据
- 如何从 API 填充数据并加载到下拉列表中
- 通过遍历JSON文件来填充数据列表选项
- 在引导模式中,点击相应的datatables行中的按钮,填充数据
- 当选择District时,PHP将从数据库中填充数据
- 从角度工厂返回数据,返回对象后填充数据
- 高图表 - 从数组填充数据
- 在承诺函数从 pouchdb 填充数据之前触发 Ionic/Angular $watch的问题
- 无法用同位素填充数据
- 使用 php 发送 json 填充数据表
- JQuery - 在表单中填充数据的正确方法
- 翡翠选择字段填充数据
- C# MVC 填充数据表中的下拉列表组
- 自动填充数据被javascript的onchange事件覆盖
- 如何在html中只使用ng repeat来填充数据,而不使用repeat html's元素
- 用Firebase和Angular填充数据表
- 通过JS Ajax调用问题填充数据
- 使用两个ajax调用在两个html表中填充数据