为什么我的GraphQL查询返回一条记录失败,但是我的查找所有记录的查询工作正常? [英] Why does my GraphQL query to return one record fail, but my query to find all records works fine?

查看:48
本文介绍了为什么我的GraphQL查询返回一条记录失败,但是我的查找所有记录的查询工作正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Mongo数据库,其中包含一个名为"words"的集合,其中包含如下文档:

I have a Mongo database with a collection called 'words' which contains documents like this:

{
  _id: "xxxx",
  word: "AA",
  definition: "Cindery lava"
}

我有一个节点应用程序,正在使用GraphQL查询和显示单词集合中的信息.我创建了一个GraphQL模式和Mongoose模型,如下所示.

I have a node app that I am using to query and display information from the words collection, with GraphQL. I have created a GraphQL schema and Mongoose model, as shown below.

// Schema
const WordType = new GraphQLObjectType({
    name: 'Word',
    fields: () => ({
        id: {type: GraphQLID},
        word: { type: GraphQLString },
        definition: { type: GraphQLString },
    })
})

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        detailsForWord: {
            type: WordType,
            args: {word: {type: GraphQLString}},
            resolve(parent, args) {
                return Word.find({word: args.word});
            }
        },
        allWords: {
            type: new GraphQLList(WordType),
            resolve(parent, args) {
                return Word.find({}).limit(100);
            }
        }
    }
});


// model 
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const wordSchema = new Schema({
    word: String,
    definition: String,
});

我的问题是"allWords"查询工作正常,但"detailsForWord"根本不工作,我也不知道为什么.

My problem is that the "allWords" query works perfectly but the "detailsForWord" does not work at all, and I have no idea why.

在GraphiQL中,我正在使用以下查询:

In GraphiQL I am using these queries:

{
  allWords {
    word
    definition
  }
}

...和

{
  detailsForWord(word: "AA") {
    word
    definition
  }
}

前者返回记录,而后者总是在GraphiQL中返回以下内容:

The former returns records, but the latter always returns the following in GraphiQL:

{
  "data": {
    "detailsForWord": {
      "id": null,
      "word": null,
      "definition": null
    }
  }
}

有什么想法为什么"detailsForWord"查询失败?

Any ideas why the "detailsForWord" query is failing?

推荐答案

显然,find返回文档数组,而findOne返回单个文档.因此,无论使用find怎样获取数组,查询都可能成功.findOne返回您要查找的文档.您的查询没有失败,它返回了一个带有数组的Promise.

Obviously find returns an array of documents while findOne returns a single document. Therefore the query might be successful you are getting an array no matter what with find. findOne returns the document you are looking for. Your query didn't fail, it returned a promise with an array.

如果您这样做

resolve(parent, args) {
            return Word.find({word: args.word}).then(c=>{console.log(c);return c})
}

您将在控制台中看到一个包含文档的数组.

You'll see an array containing the document in the console.

这篇关于为什么我的GraphQL查询返回一条记录失败,但是我的查找所有记录的查询工作正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆