I am using node, express, mongoose, and graphql.
I'm getting this error in the graphql console:
"message": "The type of SocialPostInQue.socialPost must be Output Type but got: undefined.\n\nThe type of SocialPostInQue.schedule must be Output Type but got: undefined.\n\nThe type of Mutation.addSocialPostInQue(socialPost:) must be Input Type but got: undefined.\n\nThe type of Mutation.addSocialPostInQue(schedule:) must be Input Type but got: undefined." I think the error my be origionating in the Type in the Schema.js File.
I do not know where undefined is coming from because I haven't run a query or mutation. Do you see any issues in my code?
My SocialPostInQue schema file is:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SocialPostInQueSchema = new Schema({
userId: String,
socialPost: {
id: String,
message: String,
image: {
url: String
}
},
schedule: {
month: String,
date: Number,
hour: String,
minute: String
}
});
module.exports = mongoose.model('SocialPostInQue', SocialPostInQueSchema);
And my Schema.js file is:
const axios = require('axios');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLID,
GraphQLSchema,
GraphQLList,
GraphQLNonNull
} = require('graphql');
/****** Mongoose Schemas ******/
const SOCIALPOSTINQUE = require('./socialPostInQue');
/******* Types POSSIBLE ORIGIN*******/
const SocialPostInQueType = new GraphQLObjectType({
name:'SocialPostInQue',
fields:() => ({
id: {type:GraphQLID},
userId: {type:GraphQLID},
socialPost: {
id: {type:GraphQLID},
message: {type:GraphQLString},
image: {
url: {type:GraphQLString}
}
},
schedule: {
month: {type:GraphQLString},
date: {type:GraphQLInt},
hour: {type:GraphQLString},
minute: {type:GraphQLString}
}
})
});
/****** functions ******/
const socialPostInQueList = () => {
return new Promise((resolve, reject) => {
SOCIALPOSTINQUE.find((err, socialPostsInQue) => {
if (err) reject(err)
else resolve(socialPostsInQue)
})
})
};
/****** Root Query WHERE 'SocialPostInQue.socialPost OUTPUT UNDEFINED ERROR IS******/
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
socialPostInQue: {
type: SocialPostInQueType,
args: {
id: {type:GraphQLID}
},
resolve (parentValue, {id}) {
return SOCIALPOSTINQUE.findById(id)
}
},
socialPostsInQue:{
type: new GraphQLList (SocialPostInQueType),
resolve (parentValue, args) {
return socialPostInQueList()
}
}
}
})
/***** Root Mutations WHERE 'Mutation.addSocialPostInQue...' ERRORS COME FROM*******/
const mutation = new GraphQLObjectType({
name:'Mutation',
fields:{
addSocialPostInQue:{
type: SocialPostInQueType,
args:{
userId: {type: new GraphQLNonNull (GraphQLID)},
socialPost: {
id: {type: new GraphQLNonNull (GraphQLID)},
message: {type: new GraphQLNonNull (GraphQLString)},
image: {
url: {type: new GraphQLNonNull (GraphQLString)}
}
},
schedule: {
month: {type: new GraphQLNonNull (GraphQLString)},
date: {type: new GraphQLNonNull (GraphQLInt)},
hour: {type: new GraphQLNonNull (GraphQLString)},
minute: {type: new GraphQLNonNull (GraphQLString)}
}
},
resolve(parentValue, args){
console.log('READ', args)
let newSocialPostInQue = new SOCIALPOSTINQUE({
name: args.name,
email: args.email,
age: args.age,
userId: args.userId,
socialPost: {
id: args.socialPost.id,
message: args.socialPost.message,
image: {
url: args.socialPost.image.url
}
},
schedule: {
month: args.schedule.month,
date: args.schedule.date,
hour: args.schedule.hour,
minute: args.schedule.minute
}
});
return new Promise((resolve, reject) => {
newSocialPostInQue.save(function (err) {
if(err) reject(err)
else resolve(newSocialPostInQue)
})
console.log ("New Social Post In Que Added")
});
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery,
mutation
});
All nested non-scalar types need to be constructed as object types. Note the socialPost, image and schedule fields:
const SocialPostInQueType = new GraphQLObjectType({
name:'SocialPostInQue',
fields:() => ({
id: {type:GraphQLID},
userId: {type:GraphQLID},
socialPost: new GraphQLObjectType({
name: 'SocialPostType',
fields: {
id: {type:GraphQLID},
message: {type:GraphQLString},
image: new GraphQLObjectType({
name: 'ImageType',
fields: {
url: {type:GraphQLString}
}
})
}
}),
schedule: new GraphQLObjectType({
name: 'SocialPostSchedule',
fields: {
month: {type:GraphQLString},
date: {type:GraphQLInt},
hour: {type:GraphQLString},
minute: {type:GraphQLString}
}
})
})
})
Related
I'm following along with Traversy Media's GraphQl MERN course in the section where the GraphQl schema is being defined. I'm getting errors regarding the definition of the module.exports statement, though I've checked my code against the instructor's code many times and can't find a difference.
I've looked through my code to see if there were any logical or syntax-related errors but seems to be fine for the most part.
Here is my schema.js:
//Mongoose models
const Project = require('../models/Project');
const Client = require('../models/Client');
const { GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLList, GraphQLNonNull} = require('graphql');
// Project Type
const ProjectType = new GraphQLObjectType({
name: 'Project',
fields: () => ({
id: { type: GraphQLID},
name: {type: GraphQLString},
description: {type: GraphQLString},
status: {type: GraphQLString},
client: {
type: ClientType,
resolve(parent, args)
{
return clients.findById(parent.clientId);
}
}
})
});
// Client Type
const ClientType = new GraphQLObjectType({
name: 'Client',
fields: () => ({
id: { type: GraphQLID},
name: {type: GraphQLString},
email: {type: GraphQLString},
phone: {type: GraphQLString},
})
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
projects: {
type: new GraphQLList(ProjectType),
resolve(parent, args){
return Project.find();
}
},
project: {
type: ProjectType,
args: {id: {type: GraphQLID}},
resolve(parent, args) {
return Project.findById(args.id); }
},
clients: {
type: new GraphQLList(ClientType),
resolve(parent, args){
return Client.find();
}
},
client: {
type: ClientType,
args: {id: {type: GraphQLID}},
resolve(parent, args) {
return Client.findById(args.id); }
}
}
});
//Mutations
const mutation = new GraphQLObjectType({
name: 'Mutation',
flelds: {
addClient: {
type: ClientType,
args: {
name: {
type: GraphQLNonNull(GraphQLString)
},
email: {
type: GraphQLNonNull(GraphQLString)
},
phone: {
type: GraphQLNonNull(GraphQLString)
},
},
resolve(parent, args) {
const client = new Client({
name: args.name,
email: args.email,
phone: args.phone,
});
return client.save();
},
},
},
});
module.exports = new GraphQLSchema({
query: RootQuery,
mutation,
});
index.js:
const express = require('express');
const colors = require('colors');
require('dotenv').config();
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema/schema');
const connectDB = require('./config/db');
const port = process.env.PORT || 5000;
const app = express();
//Connect to database
connectDB();
app.use('/graphql', graphqlHTTP({
schema, graphiql: process.env.NODE_ENV === 'development',
}));
app.listen(port, console.log(`Server running on port ${port}`));
and db.js:
const mongoose = require('mongoose');
const connectDB = async() => {
const conn = await mongoose.connect(process.env.MONGO_URI);
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline.bold);
};
module.exports = connectDB;
My expected result is to get a presentation of the GraphiQl interface but I receive an error stating "Mutation fields must be an object with field names as keys or a function which returns such an object."
I used mongoose and Graphql to send my queries to the database but for some reason it doesn't let me create documents. I have tried creating a new user with full admin privileges it hasn't worked I tried changing the default user password but it didn't work.
I rechecked my mongoose model no errors so what might be the problem.
FYI the problem arose with the return (author.save()) and the database connects normally
Author Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const authorSchema = new Schema({
name: String,
age: Number
});
module.exports = mongoose.model('Author', authorSchema);
schema.js
const graphql = require('graphql');
const Book = require('../models/book');
const Author = require('../models/Author');
const _ = require('lodash');
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList
} = graphql;
const BookType = new GraphQLObjectType({
name: 'Book',
fields: ( ) => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
genre: { type: GraphQLString },
author: {
type: AuthorType,
resolve(parent, args){
//return _.find(authors, { id: parent.authorId });
}
}
})
});
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: ( ) => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
age: { type: GraphQLInt },
books: {
type: new GraphQLList(BookType),
resolve(parent, args){
//return _.filter(books, { authorId: parent.id });
}
}
})
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLID } },
resolve(parent, args){
//return _.find(books, { id: args.id });
}
},
author: {
type: AuthorType,
args: { id: { type: GraphQLID } },
resolve(parent, args){
//return _.find(authors, { id: args.id });
}
},
books: {
type: new GraphQLList(BookType),
resolve(parent, args){
//return books;
}
},
authors: {
type: new GraphQLList(AuthorType),
resolve(parent, args){
//return authors;
}
}
}
});
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addAuthor: {
type: AuthorType,
args: {
name: { type: GraphQLString },
age: { type: GraphQLInt }
},
resolve(parent, args){
let author = new Author({
name: args.name,
age: args.age
});
return (author.save())
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
})
;
error message
(node:31482) MongoError: (Unauthorized) not authorized on admin to execute command {
insert: "authors", documents: [[{name gyfdgyiszukjfheusdzyih} {age 88} {_id
ObjectID("60af9c682215ea7afad86f4c")} {__v 0}]], ordered: false, writeConcern: { w:
"majority" }
Found this issue, after trying practice by GraphQL tutorial on Youtube.
To solve it, you need to update your mongoose model to the last version.
I just want to test my query mutation with Postman.
Here is my query
mutation ($input: registerSupplierInput){
registerSupplier(input: $input){
message
success
}
}
And variables:
{"email":"1#d.com", "name":"1", "address":"1", "location":[36.24,44.04], "phone_numbers":["1"]}
And here is my server schema types:
const registerSupplierInput = new GraphQLInputObjectType({
name: 'registerSupplierInput',
fields: {
name: {type: new GraphQLNonNull(GraphQLString)},
email: {type: new GraphQLNonNull(GraphQLString)},
address: {type: new GraphQLNonNull(GraphQLString)},
location: {type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLFloat)))},
phone_numbers: {type: new GraphQLList(new GraphQLNonNull(GraphQLString))},
}
});
const registerSupplierResponse = new GraphQLObjectType({
name: 'registerSupplierType',
fields: {
success: {type: new GraphQLNonNull(GraphQLBoolean)},
message: {type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString)))},
}
});
module.exports.registerSupplier = {
type: new GraphQLNonNull(registerSupplierResponse),
args: {
input: {type: registerSupplierInput}
},
async resolve(_, args){
try {
console.log(_, args);
const {registerSupplier} = require('../controllers/supplier');
return await registerSupplier(args);
}
catch(error){
return error;
}
}
}
When i request a query the args parameter returns {} in the server log.
What's wrong with my code?
I'm trying to get data from a mongodb collection using graphql and mongoose but graphql always resolves to null. This is the query I am trying:
getUser(email: "john#gmail.com"){
name
}
const userModel = new Mongoose.model("db.users", {
_id: String,
email: String,
name: String
});
const userType = new GraphQLObjectType({
name: "user",
fields : {
_id: {type: GraphQLID},
email: {type: GraphQLString},
name: {type: GraphQLString}
}
});
// Construct a schema
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name:"query",
fields: {
getUser: {
type: userType,
args: {
email: {
type: GraphQLString,
}
},
resolve: async(root, args, context, info) => {
return await(userModel.findOne(args).exec());
}
}
}
})
});
I'm new to GraphQL and trying to get a basic query setup against a mock data source that just resolves a promise with a filter to pull the record by id. I have the following:
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList
} = require('graphql')
const db = require('../db')
const getUserById = (id) => db.read(id)
const UserType = new GraphQLObjectType({
name: 'User',
description: 'User Type',
fields: () => ({
first_name: {
type: GraphQLString
},
last_name: {
type: GraphQLString
},
email: {
type: GraphQLString
},
friends: {
type: new GraphQLList(UserType),
resolve: (user) => user.friends.map(getUserById)
}
})
})
const QueryType = new GraphQLObjectType({
name: 'Query',
description: 'User Query',
fields: () => ({
user: {
type: UserType,
args: {
id: { type: GraphQLString }
}
},
resolve: (root, args) => getUserById(args.id)
})
})
const schema = new GraphQLSchema({
query: QueryType
})
module.exports = schema
When I try to run this with graphQLHTTP I get the following:
Error: Query.resolve field config must be an object
I've been following Zero to GraphQL in 30 Minutes and can't figure out what I'm doing wrong.
You've accidentally made the resolver for the user query one of the fields on the Query type. Move it inside the user field and you should be good.