[英]GraphQL query using _id String, with Object ID stored in MongoDB
Having trouble getting my graphql query to return anything when sending the _id as a string.在将 _id 作为字符串发送时,无法让我的 graphql 查询返回任何内容。 If instead, I query the DB using any other stored key (for example, name: "Account 1"), it works great and returns the object.
相反,如果我使用任何其他存储的键(例如,名称:“帐户 1”)查询数据库,它工作得很好并返回 object。 My Account schema uses type: GraphQLString for the _id, but i've also tried using GraphQLID and neither have been successful.
我的帐户架构使用类型: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))
}
}
}
});
In my MongoDB collection, the _id is stored as Object IDs.在我的 MongoDB 集合中,_id 存储为 Object ID。 Wondering if it doesn't recognize the string as the Object ID stored?
想知道它是否无法将字符串识别为存储的 Object ID? Any help is appreciated.
任何帮助表示赞赏。
Solution: mongo was not able to query the object with the _id as a string.解决方案:mongo 无法使用 _id 作为字符串查询 object。 I had to require a method to convert it to an Object ID.
我必须要求一种方法将其转换为 Object ID。
const ObjectId = require('mongodb').ObjectID;
let _idObject = ObjectId(args._id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.