在keystone中获取相关项目

时间:2014-06-12 13:58:54

标签: node.js mongoose keystonejs

在KeystoneJS中处理一个项目,我很难搞清楚猫鼬关系的位置。

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

Post.add({
    author: { type: Types.Relationship, ref: 'User' }
});

然后:

User.relationship({ path: 'posts', ref: 'Post', refPath: 'author' });

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

2 个答案:

答案 0 :(得分:3)

据我了解,keystone的List Relationship与猫鼬和查询无关。相反,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
});

你也可以尝试另一种方式,但是......

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

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

User.schema.add({ posts: { type: Types.Relationship, ref: 'Post', many: true } })

在阅读了keystone docs之后,这似乎在逻辑上等同于mongoose pure方式User.schema.add({ posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }] });。现在,您现在正在维护两个列表上的关系。相反,您可能需要在基石列表中添加method

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

通过向用户列表添加方法,可以避免将与MongoDB文档相关的ObjectId数组保存回Post文档。我知道这需要第二个查询,但这两个选项中的一个看起来是你最好的选择。

答案 1 :(得分:0)

我在他们的github上发现了这个https://github.com/Automattic/mongoose/issues/1888,检查它是否有上下文,但基本上说是使用keystone populateRelated()方法。我测试了它并且确实有效

// if you've got a single document you want to populate a relationship on, it's neater
Category.model.findOne().exec(function(err, category) {
  category.populateRelated('posts', function(err) {
    // posts is populated
  });
});

我知道这个问题已经过时了,但必须在那里进一步参考