'Express graphql mutation giving empty result after creating user
server:
const { ApolloServer, gql } = require("apollo-server-express");
const express = require("express");
const mongoose = require("mongoose");
const { userResolvers } = require("./resolvers");
const { typeDefs } = require("./typeDefs");
const startServer = async () => {
await mongoose.connect("mongodb://localhost:27017/school", {
useNewUrlParser: true,
});
const server = new ApolloServer({
typeDefs,
userResolvers,
});
await server.start();
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);
};
startServer();
resolver
const User = require("./models/userModel").Users;
const userResolvers = {
Mutation: {
addUser: (parent, args) => {
let User = new User({
name: args.name,
email: args.email,
password: args.password,
otp: args.otp,
});
return User.save();
},
},
};
module.exports = { userResolvers };
typedefs
const { gql } = require("apollo-server-express");
const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
password: String!
otp: Float!
}
type Mutation {
addUser(name: String!, email: String!, password: String!, otp: Int!): User
updateUser(
name: String!
email: String!
password: String!
otp: Int!
): User
deleteUser(id: ID!): User
}
`;
module.exports = { typeDefs };
here is my graphql code. Here i am trying to create user. But when i am creating a user in graphql it is sending null as response It is not thowing any error so it is unclear for me .
Please take a look what can be the error
I have attached the screenshot also

Solution 1:[1]
Your local definition of User
let User = new User(...);
overwrites the global definition
const User = require("./models/userModel").Users;
This should lead to an exception
Cannot access 'User' before initialization
in the addUser function, which probably causes the null response.
Use a different name for the local definition, e.g., in lower case:
let user = new User({
name: args.name,
email: args.email,
password: args.password,
otp: args.otp,
});
return user.save();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
