【发布时间】:2019-02-14 00:57:04
【问题描述】:
在this tutorial 之后,我有一个猫鼬模型:(我使用术语“帐户”而不是“待办事项”,但它是同一件事)
const Account = mongoose.model('Account', new mongoose.Schema({
id: mongoose.Schema.Types.ObjectId,
name: String
}));
还有一个 GraphQLObjectType:
const AccountType = new GraphQLObjectType({
name: 'account',
fields: function () {
return {
id: {
type: GraphQLID
},
name: {
type: GraphQLString
}
}
}
});
和一个 GraphQL 突变来创建其中之一:
const mutationCreateType = new GraphQLObjectType({
name: 'Mutation',
fields: {
add: {
type: AccountType,
description: 'Create new account',
args: {
name: {
name: 'Account Name',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, args) => {
const newAccount = new Account({
name: args.name
});
newAccount.id = newAccount._id;
return new Promise((resolve, reject) => {
newAccount.save(err => {
if (err) reject(err);
else resolve(newAccount);
});
});
}
}
}
})
运行查询后:
mutation {
add(name: "Potato")
{
id,
name
}
}
在 GraphiQL 中,我得到了响应:
{
"errors": [
{
"message": "ID cannot represent value: { _bsontype: \"ObjectID\", id: <Buffer 5b 94 eb ca e7 4f 2d 06 43 a6 92 20> }",
"locations": [
{
"line": 33,
"column": 5
}
],
"path": [
"add",
"id"
]
}
],
"data": {
"add": {
"id": null,
"name": "Potato"
}
}
}
对象创建成功,在MongoDB Compass中可以看到:
但读取值似乎有问题。
GraphQLID 和 mongoose.Schema.Types.ObjectId 的兼容性如何?如果它们不兼容,我是否误解了本教程,特别是它的用法:
newAccount.id = newAccount._id;
?我无法判断错误是由 GraphQL、MongoDB、Mongoose 还是其他东西引发的。
编辑
关于错误的任何信息
ID 不能代表值:{ _bsontype: \"ObjectID\", id: }
会非常有帮助。我觉得它告诉我它无法序列化 BSON 对象.. 但随后它显示它已序列化。即使知道产生错误的技术(mongo?mongoose?graphql?)也会有所帮助。我在 Google 上没有运气。
编辑 2
【问题讨论】:
标签: node.js mongodb mongoose graphql