gpt4 book ai didi

node.js - 当 graphQL 的查询从 mongodb 返回空数据时,你应该检查什么?

转载 作者:行者123 更新时间:2023-12-04 03:36:49 24 4
gpt4 key购买 nike

我正在尝试将 Flask api 转换为 graphql 服务器。我可以获得示例代码来处理测试 mongodb 集合,但我无法让我的改编代码在真正的 mongodb 服务器上工作。查询始终返回空数据响应。调试此代码的步骤是什么? enter image description here

const Express = require("express");
const { graphqlHTTP } = require('express-graphql');
const Mongoose = require("mongoose");
const {
GraphQLID,
GraphQLString,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema
} = require("graphql");

var app = Express();

Mongoose.connect("mongodb://localhost/treasure-chess");

//"persons" is the collection
const GameModel = Mongoose.model("game", {
black: String,
white: String
});

const GameType = new GraphQLObjectType({
//the name field here doesn't matter I guess...
name: "Game",
fields: {
id: { type: GraphQLID },
black: { type: GraphQLString },
white: { type: GraphQLString }
}
});

const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "Query",
fields: {
games: {
type: GraphQLList(GameType),
resolve: (root, args, context, info) => {
return GameModel.find().exec();
}
},
game: {
type: GameType,
args: {
id: { type: GraphQLNonNull(GraphQLID) }
},
resolve: (root, args, context, info) => {
return GameModel.findById(args.id).exec();
}
}
}
}),
mutation: new GraphQLObjectType({
name: "Mutation",
fields: {
game: {
type: GameType,
args: {
firstname: { type: GraphQLNonNull(GraphQLString) },
lastname: { type: GraphQLNonNull(GraphQLString) }
},
resolve: (root, args, context, info) => {
var game = new GameModel(args);
return game.save();
}
}
}
})
});

app.use("/graphql", graphqlHTTP({
schema: schema,
graphiql: true
}));


app.listen(3000, () => {
console.log("Listening at :3000...");
});

证明我正在连接到正确的 mongodb 文档:

enter image description here

更多证明:

enter image description here

我确实尝试了评论建议,结果发现结果是空的……:

                    var results = GameModel.find().exec()
results.then(game_info =>{
console.log(game_info)
})

最佳答案

我在 stackoverflow 上尝试了一系列不同的搜索后找到了答案。事实证明,mongoose.model 假定您传递的任何参数都是单数,并且默认情况下将其复数。所以我实际上必须传入:

const GameModel = Mongoose.model("game", gameSchema, "game");

如果大多数人可能不会遇到此错误,因为他们可能会考虑到这一点来命名他们的收藏,可能会有一个奇怪的人想要为他们的收藏使用不同的名称,或者该收藏的复数是相同的单数。我会把它留给其他人,祝您编码愉快!

关于node.js - 当 graphQL 的查询从 mongodb 返回空数据时,你应该检查什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66728288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com