簡體   English   中英

多對多關系-在查詢中填充相關數據-Keystonejs

[英]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才能參考,但對於無法使用的前端用戶來說,則是必須的。

謝謝

您可以輕松地創建所需的內容,因此不要氣our。 您只需要了解貓鼬中的'.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.relationship({})選項(向用戶顯示了在后端引用該群組的用戶)

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.users都將返回以下內容:

[
  {
    _id: '',
    name: '',
    ...
    groups: [
      {
        _id: '',
        name: ''
        ...
      }
    ]
  }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM