javascript - 为什么我的 GraphQL 查询返回一条记录失败,但我的查询查找所有记录却工作正常?

标签 javascript mongoose graphql

我有一个 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”查询失败的原因吗?

最佳答案

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

如果你这样做

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

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

关于javascript - 为什么我的 GraphQL 查询返回一条记录失败,但我的查询查找所有记录却工作正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53108686/

相关文章:

javascript - $inc of mongoose 防止负值

javascript - 尝试使用 react-apollo-hooks 在函数中调用 useQuery

javascript - "event.originalEvent.clipboardData.getData"是什么意思?

"fiddle"中未调用 Javascript 函数

node.js - 是否可以在 mongoosejs 模式中填充自引用?

javascript - GraphQL 术语 "fieldAST"的起源是什么

vue.js - 如何将动态参数添加到 graphql 查询中

javascript - 不推荐使用 getUserData() 或 setUserData()

javascript - 扁平结构到树结构

node.js - mongoose.model 函数中的名称与 mongodb 中的集合名称不同