我有两个集合:
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请求 . 这是目标:
如果您只需要具有其作品 Headers 的作者列表,则所有必需字段都在dbAuthors中,因此无需查找dbPosts . 但是如果你需要更多关于返回的帖子的详细信息,比如摘录或slug,你会在以下情况下查找dbPosts:
{'author.id': parent.id}
但问题是,如果您的查询如下所示:
authors(id: "3") {
fname
lname
posts {
title
excerpt
}
}
它会中断,因为父对象中没有返回 excerpt 字段 . 如果有某种方法我可以确定在作者's posts field and then decide if the values returned in parent would suffice. If not, I could then proceed to look up dbPosts with the author'的id值上查询哪些字段,则可以轻松修复此问题 . 可能吗?因为如果没有,它会破坏你的收藏品非正规化的整个目的,Mongo强烈要求你这样做!