【问题标题】:Why does my GraphQL query to return one record fail, but my query to find all records works fine?为什么我的 GraphQL 查询返回一条记录失败,但我查找所有记录的查询工作正常?
【发布时间】:2019-04-06 02:45:06
【问题描述】:

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

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

我有一个节点应用程序,我用它来查询和显示来自单词集合的信息,使用 GraphQL。我已经创建了一个 GraphQL 模式和 Mongoose 模型,如下所示。

// 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”根本不工作,我不知道为什么。

在 GraphiQL 中,我使用这些查询:

{
  allWords {
    word
    definition
  }
}

...和

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

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

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

知道为什么“detailsForWord”查询失败了吗?

【问题讨论】:

  • 更新:原来 Word.findOne(word: "AA") 有效!我仍然不知道为什么 Word.find({word: "AA") 不起作用。

标签: javascript mongoose graphql


【解决方案1】:

显然 find 返回一个文档数组,而 findOne 返回一个文档。因此查询可能会成功,无论使用什么查找,您都会得到一个数组。 findOne 返回您正在查找的文档。您的查询没有失败,它返回了一个带有数组的承诺。

如果你这样做了

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多