【发布时间】:2019-02-23 09:43:21
【问题描述】:
我有两个收藏:
dbPosts
id: mongoose.Schema.Types.ObjectId,
title: { type: String },
content: { type: String },
excerpt: { type: String },
slug: { type: String },
author: {
id: { type: String },
fname: { type: String },
lname: { type: String },
}
dbAuthors
id: mongoose.Schema.Types.ObjectId,
fname: { type: String },
lname: { type: String },
posts: [
id: { type: String },
title: { type: String }
]
我按如下方式解决我的作者查询:
Query: {
authors: (parent, root, args, context) => {
return dbAuthor.find({});
},
author: (root, args, context) => {
return dbAuthor.findById(args.id);
},
},
Author: {
posts: (parent) => {
if(parent.posts) {
return parent.posts;
} else {
return dbAuthor.find({'author.id': parent.id});
}
},
}
我这样解决的原因是通过非规范化我的关系来优化我的 MongoDB 请求。这是目标:
如果您只需要包含作品标题的作者列表,所有必要的字段都在 dbAuthors 中,因此无需查找 dbPosts。但是,如果您需要有关返回的每个帖子的更多详细信息,例如摘录或 slug,您可以查找 dbPosts 以了解以下情况:
{'author.id': parent.id}
但问题是,如果您的查询如下所示:
authors(id: "3") {
fname
lname
posts {
title
excerpt
}
}
它会中断,因为父对象中没有返回 excerpt 字段。如果有某种方法我可以确定在作者的帖子字段上查询哪些字段,然后确定在 parent 中返回的值是否足够,则可以轻松解决此问题。如果没有,我可以继续使用作者的 id 值查找 dbPosts。可能吗?因为如果不是这样,它将破坏非规范化集合的整个目的,Mongo 强烈敦促您这样做!
【问题讨论】:
标签: graphql