【发布时间】:2021-06-18 01:11:17
【问题描述】:
我正在尝试将 Flask api 转换为 graphql 服务器。我可以让示例代码与测试 mongodb 集合一起使用,但我无法让我改编的代码在真正的 mongodb 服务器上工作。查询始终返回空数据响应。调试此代码的步骤是什么?
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 文档:
更多证据:
我确实尝试了评论建议,结果发现结果是空的……:
var results = GameModel.find().exec()
results.then(game_info =>{
console.log(game_info)
})
【问题讨论】:
-
你应该检查数据库响应...
console.log( GameModel.find().exec() ); -
您好,谢谢您的建议。似乎 db 响应为空?
标签: node.js mongodb api graphql