通过 _id 使用 graphQL 获取数据

Fetching data with qraphQL by _id

我最近开始使用 GraphQL。我可以使用名称的基础从 mongodb 集合中获取记录,但是如果我尝试使用相同的代码通过 _id(mongodb generated id) 获取数据,我将获得所有字段的空值。 这是我的示例代码...

query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
    // To get a user based on id
      getUser: {
        type: UserType,
        args: {
          _id: {
            description: 'The username of the user',
            type: new GraphQLNonNull(GraphQLString)
          }
        },

       resolve: (root, {_id}) => {
         //Connect to Mongo DB
        return mongo()
            .then(db => { 
             return  new Promise(
              function(resolve,reject){
                 //Query database
                 let collection = db.collection('users');
                 collection.findOne({ _id},(err,userData) => {             
                  if (err) {
                    reject(err);
                    return;
                  } 
                  console.log(userData);
                  resolve(userData);
                });
               })
             });
            }
          },

示例查询是:

{ 
      getUser ( _id: "55dd6300d40f9d3810b7f656") 
      {  
               username,
               email,
               password
      } 
}

我收到的回复如下:

{
    "data": {
        "getUser": null
    }
}

如果需要,请建议我进行任何修改... 谢谢

因为mongoDB生成的“_id”字段不仅仅是一个字符串,它实际上是ObjectId("YOUR ID STRING HERE").

因此在您的查询中,mongoDB 找不到任何与您输入的字符串相同的 _id。

尝试改用 collection.findById()。