node.js - Node.js Mongodb GraphQL - 突变和查询
问题描述
我的代码的某些部分有问题:
const BookType = new GraphQLObjectType({
name: "Book",
fields: () => ({
id: {type: GraphQLID},
title: {type: GraphQLString},
author: {type: GraphQLString},
})
})
const fQuery = new GraphQLObjectType({
name: "firstQuery",
fields: {
books: {
type: new GraphQLList(BookType),
resolve(parent, args){
return Book.find({});
}
},
book: {
type: BookType,
args: {id: {type: GraphQLID}},
resolve(parent, args){
return Book.findById(args.id);
}
},
author: {
type: BookType,
args: {author: {type: GraphQLString}},
resolve(parent, args){
return ??????????
}
},
}
})
我不知道如何找到作者的书。下一件事 - 突变:
const Mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
add: {
type: BookType,
args: {
title: {type: GraphQLString},
author: {type: GraphQLString},
},
resolve(parent,args){
let book = new Book({
title:args.title,
author:args.author,
})
return book.save()
}
},
update: {
type: BookType,
args: {
title: {type: GraphQLString},
author: {type: GraphQLString},
},
resolve(parent, args){
return Book.findByIdAndUpdate(args.id, {
title: args.title,
author: args.author
})
}
},
del: {
type: BookType,
args: {
id: {type: GraphQLID},
},
resolve(parent,args){
return Book.findByIdAndDelete(args.id)
}
}
}
});
更新不起作用。删除删除第一个项目,而不是按 ID 选择的项目。这是我的家庭作业。我已经坐了几个小时了,似乎无法正确处理。你们中有人知道如何解决这个问题吗?提前致谢!
更新:按作者搜索不起作用。我能够解决其余的问题。
解决方案
您还需要一个作者 GraphQLObjectType,如果您将作者的 id 存储在您的书籍中,您可以在作者中添加一个新字段
编辑:您也可以尝试按名称查找(但它必须是唯一的,否则您将得到冲突的结果)
booksByAuthor: {
type: GraphQLList(BookType),
async resolve(parent, args) {
return Books.find( { id:parent.id } )
},
}
所以会是这样的
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
booksByAuthor: {
type: GraphQLList(BookType),
async resolve(parent, args) {
return Books.find({ id: parent.id });
},
},
}),
});
我没有将 id 视为您的突变中的参数。您需要传递 id。
update: {
type: BookType,
args: {
id:{type: GraphQLID}
title: {type: GraphQLString},
author: {type: GraphQLString},
},
resolve(parent, args){
return Book.findByIdAndUpdate(args.id, {
title: args.title,
author: args.author
})
}
},
我也是新手,但我希望它有所帮助
推荐阅读
- android - 如何使不规则形状的组件可点击?安卓
- node.js - Nedb 查找一项并更改另一项
- python - 错误: ('IM005', "[IM005] [unixODBC][Driver Manager]Driver's SQLAllocHandle on SQL_HANDLE_DBC failed (0) (SQLDriverConnect)")
- here-api - 反向地理编码:响应中的城市与国家相同?
- hibernate - 使用 EclipseLink 使用 JOIN ... ON 子句 + 子查询导致异常“编译时遇到内部问题”的 JPQL 查询
- hadoop - Hive 插入覆盖所有分区
- javascript - 将 getFullYear 方法转换为 Integer
- javascript - MongoDB 如何通过帖子获取用户
- c++ - 堆异常 -1073741510 对象
- django - Plesk 乘客 django 观看 manage.py 日志