【问题标题】:GraphQL query using _id String, with Object ID stored in MongoDB使用 _id 字符串的 GraphQL 查询,对象 ID 存储在 MongoDB 中
【发布时间】:2021-03-14 20:35:41
【问题描述】:

在将 _id 作为字符串发送时,无法让我的 graphql 查询返回任何内容。相反,如果我使用任何其他存储的键(例如,名称:“帐户 1”)查询数据库,它工作得很好并返回对象。我的帐户架构使用类型:GraphQLString 作为_id,但我也尝试过使用 GraphQLID,但都没有成功。

const AccountType = new GraphQLObjectType({
    name: 'Account',
    fields: () => ({
        _id: { type: GraphQLString },
        name: { type: GraphQLString },
        balance: { type: GraphQLInt },
    })
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        getAccounts: {
            type: AccountType,
            args: { _id: { type: GraphQLString } },
            async resolve(parentValue, args, context) {
                console.log(args._id)
                return context.mongo.Accounts.findOne({ _id: args._id })
                    .then(response => console.log(response))
            }
        }
    }
});

在我的 MongoDB 集合中,_id 存储为对象 ID。想知道它是否无法将字符串识别为存储的对象 ID?任何帮助表示赞赏。

【问题讨论】:

  • 你也可以去掉_id的下划线,因为mongodb能够成功解析它

标签: javascript reactjs mongodb graphql


【解决方案1】:

解决方案:mongo 无法使用 _id 作为字符串查询对象。我必须要求一种方法将其转换为对象 ID。

const ObjectId = require('mongodb').ObjectID;
let _idObject = ObjectId(args._id)

【讨论】:

    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 2016-07-04
    • 2014-12-13
    • 2016-01-23
    • 2019-10-30
    • 2018-09-09
    • 2017-07-31
    相关资源
    最近更新 更多