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());
}
}
}
})
});
Related
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 am currently building mern + graphql app. I am new to graphql and I have two different models a User Model and Character model. The Character Model is nested in the User. When I create a user in the Graphiql interface I want it to display its data and the character that is associated with the specific user but instead it is displaying every character that has been created in the database and adding them to every user created instead of the specific user. Trying to figure out how to fix this. Link to Github Repo
Mongoose User Model
const mongoose = require('../db/connection')
const Schema = mongoose.Schema
const User = new Schema({
id: String,
name: String,
totalwins: Number,
description: String,
charactersID: [
{
type: Schema.Types.ObjectId,
ref: "Character"
}
]
})
module.exports = mongoose.model('User', User)
Mongoose Character Model
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Character = new Schema({
name: String,
wins: Number,
losses: Number,
percentage: Number,
image: String
})
module.exports = mongoose.model('Character', Character)
const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLID, GraphQLList,
GraphQLNonNull } = graphql
const Character = require("../models/Character")
const User = require("../models/User")
Types
// User Schema
const userType = new GraphQLObjectType({
name: 'User',
fields : () => ({
_id: {type: GraphQLID},
name : { type: GraphQLString},
totalwins : { type: GraphQLInt },
description : { type: GraphQLString },
character : {
type : new GraphQLList(characterType),
resolve(parent, args){
return Character.find({charactersID: parent.id})
}
}
})
})
// Character Schema
const characterType = new GraphQLObjectType({
name: 'Character',
fields : () => ({
id: {type: GraphQLID},
name : { type: GraphQLString},
wins : { type: GraphQLInt },
losses : { type: GraphQLInt },
percentage: {type: (GraphQLInt)},
image: { type: GraphQLString },
})
})
Query
//query the graph to grab the data
const Query = new GraphQLObjectType({
name: 'Query',
fields: {
user : {
type: userType,
// arguments passed by the user while making the query
args: {id : {type : GraphQLID}},
resolve(parent, args){
// return User.find((item) => { return item.id == args.id});
//finding a single user by id
return User.findById(args.id)
}
},
users : {
type: new GraphQLList(userType),
resolve(parent, args) {
return User.find({})
}
},
character : {
type: characterType,
args: {id : {type : GraphQLID}},
resolve(parent, args){
return Character.findById(args.id)
}
},
characters : {
type: new GraphQLList(characterType),
resolve(parent, args) {
return Character.find({})
}
}
}
})
Mutations
//allows user to add, update and delete to mondodb through graphql
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addUser: {
type: userType,
args: {
name: {type: GraphQLNonNull(GraphQLString)},
totalwins: {type: (GraphQLInt)},
description: {type: (GraphQLString)},
charactersID: { type: new GraphQLNonNull(GraphQLID)}
},
resolve(parent, args){
let user = new User({
name: args.name,
totalwins: args.totalwins,
description: args.description,
charactersID: args.charactersID
})
return user.save()
}
},
addCharacter: {
type: characterType,
args: {
name: {type: GraphQLNonNull(GraphQLString)},
wins: {type: (GraphQLInt)},
losses: {type: (GraphQLInt)},
percentage: {type: (GraphQLInt)},
image: {type: (GraphQLString)},
},
resolve(parent, args){
let character = new Character({
name: args.name,
wins: args.wins,
losses: args.losses,
percentage: args.percentage,
image: args.image
})
return character.save()
}
},
deleteUser: {
type: userType,
args: {
id: {type: new GraphQLNonNull(GraphQLString)}
},
resolve(parent, args){
const remUser = User.findByIdAndRemove(args.id)
if(!remUser){
throw new Error('No character found')
}
return remUser
}
},
deleteCharacter: {
type: characterType,
args: {
id: {type: new GraphQLNonNull(GraphQLString)}
},
resolve(parent, args){
const remCharacter = Character.findByIdAndRemove(args.id)
if(!remCharacter){
throw new Error('No character found')
}
return remCharacter
}
},
}
})
module.exports = new GraphQLSchema({ query : Query, mutation : Mutation})
Image of results from Grapiql interface
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}
}
})
})
})
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.