最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - GraphQL MongoDB data null output in createUser - Stack Overflow

programmeradmin1浏览0评论

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);

发布评论

评论列表(0)

  1. 暂无评论