I'm having a trouble on how to create a simple CRUD with GraphQL + MongoDB first start with the creating a user.
In my postman, I type this in GraphQL Query
mutation CreateUser($username: String!, $email: String!) {
createUser(username: $username, email: $email) {
id
username
email
}
}
And this is the variable
{
"username": "Alice",
"email": "[email protected]"
}
Now my output error here is this.
{
"data": {
"createUser": null
}
}
So I don't understand where is the error coming up in any of this files?? This are the files..
And this is my resolvers.js
const User = require('./models/User');
const resolvers = {
Query: {
users: async () => await User.find(),
user: async (_, { id }) => await User.findById(id),
},
Mutation: {
createUser: async (_, { username, email }) => {
try {
const newUser = new User({ username, email });
await newUser.save();
return newUser;
} catch (error) {
console.error('Error creating user:', error);
throw new Error('Failed to create user');
}
},
updateUser: async (_, { id, username, email }) => {
try {
const updatedUser = await User.findByIdAndUpdate(
id,
{ username, email },
{ new: true }
);
if (!updatedUser) throw new Error('User not found');
return updatedUser;
} catch (error) {
console.error('Error updating user:', error);
throw new Error('Failed to update user');
}
},
deleteUser: async (_, { id }) => {
try {
const deletedUser = await User.findByIdAndDelete(id);
if (!deletedUser) throw new Error('User not found');
return true;
} catch (error) {
console.error('Error deleting user:', error);
throw new Error('Failed to delete user');
}
},
},
};
module.exports = resolvers;
typeDefs.js
const typeDefs = `#graphql
type User {
id: ID!
username: String!
email: String!
}
type Query {
users: [User!]!
user(id: ID!): User
}
type Mutation {
createUser(username: String!, email: String!): User
updateUser(id: ID!, username: String, email: String): User
deleteUser(id: ID!): Boolean
}
`;
module.exports = { typeDefs };
User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: String,
email: String,
});
// Transform _id to id and remove __v when converting to JSON
userSchema.method('toJSON', function() {
const { _id, __v, ...object } = this.toObject();
object.id = _id.toString();
return object;
});
module.exports = mongoose.model('User', userSchema);