Fac*_*teo 7 javascript reactjs graphql graphql-js relayjs
我正在尝试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],
})
Run Code Online (Sandbox Code Playgroud)
所以,当我要求这样的文章时:
{
article(id: 1) {
id,
title,
author
}
}
Run Code Online (Sandbox Code Playgroud)
它会对数据库进行3次查询吗?我的意思是,每个字段都有一个解析方法(getTitle,getAuthor ...),它向数据库发出请求.我做错了吗?
这是getAuthor的一个例子(我使用mongoose):
articleSchema.methods.getAuthor = function(id){
let article = this.model('Article').findOne({_id: id})
return article.author
}
Run Code Online (Sandbox Code Playgroud)
如果该resolve方法传递给article,您不能只访问该属性吗?
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.title,
},
author: {
type: userConnection,
description: 'The author of the article',
resolve: (article) => article.author,
},
}),
interfaces: [nodeInterface],
})
Run Code Online (Sandbox Code Playgroud)
由于Schema.methodsMongoose 在model 上定义了方法,因此它不需要文章的 ID(因为您在文章实例上调用它)。因此,如果您想保留该方法,只需执行以下操作:
articleSchema.methods.getAuthor = function() {
return article.author;
}
Run Code Online (Sandbox Code Playgroud)
如果您需要在另一个集合中查找它,那么您需要执行单独的查询(假设您不使用引用):
articleSchema.methods.getAuthor = function(callback) {
return this.model('Author').find({ _id: this.author_id }, cb);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1921 次 |
| 最近记录: |