【问题标题】:Fetching data with qraphQL by _id通过 _id 使用 graphQL 获取数据
【发布时间】:2015-11-27 13:41:56
【问题描述】:

我最近开始使用 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
    }
}

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

【问题讨论】:

    标签: node.js mongodb graphql


    【解决方案1】:

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

    所以在您的查询中,mongoDB 不会找到任何与您提供给它的字符串相等的 _id。

    尝试使用 collection.findById() 代替。

    【讨论】:

      猜你喜欢
      • 2020-01-20
      • 2019-05-03
      • 2021-11-05
      • 1970-01-01
      • 2021-07-02
      • 2021-02-17
      • 2018-08-21
      • 2019-08-28
      • 1970-01-01
      相关资源
      最近更新 更多