Reputation: 107
I'm attempting to translate a Flask api to a graphql server. I can get example code to work with a test mongodb collection but I cannot get my adapted code to work on the real mongodb server. The query always returns an empty data response. What are the steps to debug this code?
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...");
});
Proof that I'm connecting to the right mongodb document:
More proof:
I did attempt the comment suggestion only to find that the result was empty...:
var results = GameModel.find().exec()
results.then(game_info =>{
console.log(game_info)
})
Upvotes: 3
Views: 653
Reputation: 107
I found the answer after trying a bunch of different searches on stackoverflow. It turns out that mongoose.model assumes that whatever parameter you pass is singular and pluralizes it by default. So I actually had to pass in:
const GameModel = Mongoose.model("game", gameSchema, "game");
Granted most people probably won't experience this error as they probably named their collections with this in mind, there might be the one odd person who wanted to utilize a different name for their collection OR the plural of the collection is the same singular. I'll leave this up for others, happy coding!
Upvotes: 1