我有一个 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/