在keystone中获取相关项目

Que*_*lan 6 mongoose node.js keystonejs

在KeystoneJS的一个项目上工作,我很难搞清楚猫鼬关系的位置.

根据keystone docs,假设我们有以下模型:UserPost.现在帖子与用户有关系,所以我会写:

Post.add({
    author: { type: Types.Relationship, ref: 'User' }
});
Run Code Online (Sandbox Code Playgroud)

然后:

User.relationship({ path: 'posts', ref: 'Post', refPath: 'author' });
Run Code Online (Sandbox Code Playgroud)

现在,我希望能够看到有关该用户的所有帖子,而无需查询两个用户帖子.例如,如果我查询了一个用户对象,我希望能够user.posts访问这些相关帖子.你能用mongoose/keystone做到这一点吗?

Eat*_*oes 4

据我了解,keystone的列表关系与猫鼬和查询无关。相反,keystone 的管理 UI 使用它来构建关系查询,然后再将它们呈现在视图中。这就是说我会忘记User.relationship(...);解决你的问题,尽管你想要它达到我刚才提到的目的。

根据您的架构,以下内容应该可以正常工作,但仅填充侧面的关系one

var keystone = require('keystone');
keystone.list('Post').model.findOne().populate('author', function (err, doc) {
  console.log(doc.author.name); // Joe
  console.log(doc.populated('author'));  // '1234af9876b024c680d111a1' -> _id
});
Run Code Online (Sandbox Code Playgroud)

您也可以尝试其他方式,但是......

keystone.list('User').model.findOne().populate('posts', function (err, doc) {
  doc.posts.forEach(function (post) {
    console.log(post);
  });
});
Run Code Online (Sandbox Code Playgroud)

...mongoose 期望将此定义添加到Schema中。通过在用户列表文件中包含以下行来添加此关系:

User.schema.add({ posts: { type: Types.Relationship, ref: 'Post', many: true } })
Run Code Online (Sandbox Code Playgroud)

阅读了 keystone 文档后,这在逻辑上似乎等同于 mongoose pure way User.schema.add({ posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }] });,. 现在您正在维护两个列表上的关系。相反,您可能想将一个方法添加到您的梯形校正列表中。

User.schema.methods.posts = function(done){
  return keystone.list('Post').model.find()
    .where('author', this.id )
    .exec(done);
};
Run Code Online (Sandbox Code Playgroud)

通过向您的用户列表添加一个方法,您可以免于保留将ObjectIdMongoDB 文档关联回 Post 文档的数组。我知道这需要第二次查询,但这两个选项之一看起来是您最好的选择。