[英]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.