I am learning graphql so please have patience with me.
My app.js looks like this:
const express = require('express');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');
const { buildSchema } = require('graphql');
const mongoose = require('mongoose');
const Event = require("./models/event");
const app = express();
app.use(bodyParser.json());
app.use('/graphql', graphqlHttp({
schema: buildSchema(`
type Event{
_id: ID!
title: String!
description: String!
price: Float!
date: String!
}
input EventInput{
title: String!
description: String!
price: Float!
date: String!
}
type RootQuery{
events: [Event!]!
}
type RootMutation {
createEvent(eventInput: EventInput): Event
}
schema {
query: RootQuery
mutation: RootMutation
}
`),
rootValue: {
events: () => {
return events;
},
createEvent: args => {
const event = new Event({
title: args.eventInput.title,
description: args.eventInput.description,
price: +args.eventInput.price,
date: new Date(args.eventInput.date)
});
return event
.save()
.then(result => {
console.log(result);
return {...result._doc};
})
.catch(err => {
console.log(err);
throw err;
});
}
},
graphiql: true
}));
mongoose.connect(`mongodb://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@localhost:27017/graphqldb`, {useNewUrlParser: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection errror:'));
db.once('open', function(){
console.log('Connection open');
app.listen(5000);
});
and my event.js looks like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const eventSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
date: {
type: Date,
required: true
}
});
module.exports = mongoose.model('Event', eventSchema);
when I tried to very it, by accessing the URL: http://localhost:5000/graphql
mutation {
createEvent(eventInput: {title: "title", description: "description", price: 9.99, date: "2019-05-15T08:04:26.461Z"})
}
I encounter an error related to subfields:
{ "errors": [ { "message": "Field \"createEvent\" of type \"Event\" must have a selection of subfields. Did you mean \"createEvent { ... }\"?", "locations": [ { "line": 3, "column": 3 }
Please let me know what I am missing. As I understand my field does not contain any subfields.
Thank you in advance.
UPDATE:
This is not a duplicate from the questions posted. As you can see in my mutation, I supplied all the required fields but still I recieved this error.
The error happened only when I tried to use mongoose but before it is working as expected.