gpt4 book ai didi

node.js - 跨 Mongoose 和 GraphQL 的 ObjectId 字段使用的正确类型是什么?

转载 作者:可可西里 更新时间:2023-11-01 09:28:42 27 4
gpt4 key购买 nike

正在关注 this tutorial ,我有一个 Mongoose 模型:(我使用术语“帐户”而不是“待办事项”,但它是同一回事)

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中可以看到:

From MongoDB Compass showing created object

但读取值似乎有问题。

GraphQLIDmongoose.Schema.Types.ObjectId 的兼容性如何?如果它们不兼容,我是否误解了教程,特别是它使用:

newAccount.id = newAccount._id;

?我无法确定该错误是由 GraphQL、MongoDB、Mongoose 还是完全由其他东西引发的。

编辑

有关错误的任何信息

ID cannot represent value: { _bsontype: \"ObjectID\", id: }

非常有帮助。我觉得它告诉我它无法序列化 BSON 对象 .. 但随后它显示它已序列化。即使知道产生错误的技术(mongo?mongoose?graphql?)也会有所帮助。我在 Google 上运气不好。

编辑 2

这是由 a change 引起的到最近介绍的graphql包,有a PR等待解决它的合并。

最佳答案

我没有发现问题并使用我现有的代码库之一运行此代码。除了我将突变包装在 GraphQLObjectType 中。

const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addAccount: {
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);
});
});
}
}
});

获取工作示例:Clone repo 协议(protocol)。在此 repo 中,应用程序使用 v0.13.2,您使用的是通过 npm i graphql 安装的 v14.0.2。将 graphql 降级到 v0.13.2

关于node.js - 跨 Mongoose 和 GraphQL 的 ObjectId 字段使用的正确类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52243415/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com