i am beginner in Graph Ql.but i am trying to create a grapghql server with node and express as follow...
const graphql = require('graphql');
const _ = require('lodash')
const { GraphQlObjectType, GraphQLString,GraphQLSchema,buildSchema } =
graphql;
var books=[
{name:'Hezaro yek Shab',gener:'romans',id:1},
{name:'Fergosen memorizes',gener:'sport',id:2},
{name:'Hpliday physics',gener:'sience',id:3}
];
const BookType = new GraphQlObjectType({
name: 'Book',
fields: () => ({
id: { type: GraphQLString },
title: { type: GraphQLString },
gener: { type: GraphQLString }
})
});
const RootQuery=new GraphQlObjectType({
name:'RootQueryType',
fields:{
book:{
type:BookType,
args:{ id: { type: GraphQLString }},
resolve(parent,args){
return _.find(books,{id:args.id});
}
}
},
});
module.exports=new GraphQLSchema({
query:RootQuery
});
i used GraphQlObjectType to create schema for book and for Root Query and then passed book type into Root Query type as well .
any way i want to find particular book in array of books (data dont come from database at this time -just from local array)
but i have this error
The GraphQlObjectType is not a constructor error because of a typo, change it to GraphQLObjectType.
Related
I am trying to use a query in NodeJS using mongoose + GraphQL.
The model file as:
const mongoose = require('mongoose')
mongoose.set('debug', true);
const Schema = mongoose.Schema
const authorSchema = new Schema({
name: String,
age: Number,
authorId: String,
})
module.exports = mongoose.model('Author', authorSchema)
Schema for author is as below:
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: () => ({
authorId: {type: GraphQLString},
name: {type: GraphQLString},
age: {type: GraphQLInt},
books: {
type: new GraphQLList(BookType),
resolve(parent, args) {
return book.find({authorId: parent.authorId})
}
},
})
})
The rootQuery:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
author: {
type: AuthorType,
args: {authorId: {type: GraphQLString}},
resolve(parent, args){
console.log("Author parent", parent, args)
return Author.find({authorId: args.authorId})
}
},
Now when I am trying to use query from graphiQL using authorId, it returns as null, I have enabled mongoose debug, I see that mongoose sending correct query.
{
author(authorId: "1") {
name
age
authorId
}
}
It returns below
{
"data": {
"author": {
"name": null, <<<<
"age": null, <<<
"authorId": null <<<
}
}
}
But I see that in mongoose log, it sends correctly
Mongoose: authors.find({ authorId: '1' }, { projection: {} })
In my mongo db, I have the data for authorId as below:
Atlas atlas-5p0amv-shard-0 [primary] test> db.authors.find({authorId: '1'})
[
{
_id: ObjectId("63adf57d50ee6abd7cce79ad"),
name: 'Author1',
age: 44,
authorId: '1',
__v: 0
}
]
Atlas atlas-5p0amv-shard-0 [primary] test>
Can you please let me know where I am doing wrong.
Thanks in advance.
With Regards,
-M-
As per the comment above, you want Author.findOne not Author.find since you'd want a single document, not an array.
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'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.