繁体   English   中英

GraphQL 查询使用 _id 字符串,Object ID 存储在 MongoDB

[英]GraphQL query using _id String, with Object ID stored in MongoDB

在将 _id 作为字符串发送时,无法让我的 graphql 查询返回任何内容。 相反,如果我使用任何其他存储的键(例如,名称:“帐户 1”)查询数据库,它工作得很好并返回 object。 我的帐户架构使用类型: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 存储为 Object ID。 想知道它是否无法将字符串识别为存储的 Object ID? 任何帮助表示赞赏。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM