我正在尝试Relay和GraphQL.当我在做模式时,我这样做:
let articleQLO = new GraphQLObjectType({ name: 'Article',description: 'An article',fields: () => ({ _id: globalIdField('Article'),title: { type: GraphQLString,description: 'The title of the article',resolve: (article) => article.getTitle(),},author: { type: userConnection,description: 'The author of the article',resolve: (article) => article.getAuthor(),}),interfaces: [nodeInterface],})
所以,当我要求这样的文章时:
{ article(id: 1) { id,title,author } }
它会对数据库进行3次查询吗?我的意思是,每个字段都有一个解析方法(getTitle,getAuthor …),它向数据库发出请求.我做错了吗?
这是getAuthor的一个例子(我使用mongoose):
articleSchema.methods.getAuthor = function(id){ let article = this.model('Article').findOne({_id: id}) return article.author }
解决方法
如果通过了解决方法的文章,你不能只访问该属性吗?
let articleQLO = new GraphQLObjectType({ name: 'Article',resolve: (article) => article.title,resolve: (article) => article.author,})
由于Mongoose中的Schema.methods定义了模型上的方法,因此它不需要文章的ID(因为您在文章实例上调用它).所以,如果你想保留这个方法,你会这样做:
articleSchema.methods.getAuthor = function() { return article.author; }
如果是你需要查找的东西,例如在另一个集合中,那么你需要做一个单独的查询(假设你没有使用refs):
articleSchema.methods.getAuthor = function(callback) { return this.model('Author').find({ _id: this.author_id },cb); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。