Node.js GraphQL-无法为不可为空的字段RootMutation.createUser返回null

时间:2020-09-13 08:26:39

标签: node.js graphql

我正在尝试在我的node.js应用程序中运行此简单的Graphql测试。但这给了我“无法为不可为空的字段RootMutation.createUser返回null”的错误。

schema.js 代码

const { buildSchema } = require('graphql');

module.exports = buildSchema(`
    type Post {
        _id: ID!
        title: String!
        content: String!
        imageUrl: String!
        creator: User!
        createdAt: String!
        updatedAt: String!
    }

    type User {
        _id: ID!
        name: String!
        email: String!
        password: String
        status: String!
        posts: [Post!]!
    }

    input UserInputData {
        email: String!
        name: String!
        password: String!
    }

    type RootQuery {
        hello: String
    }

    type RootMutation {
        createUser(userInput: UserInputData): User!
    }

    schema {
        query: RootQuery
        mutation: RootMutation
    }
`);

resolvers.js 代码

const bcrypt = require('bcryptjs');

const User = require('../models/user');

module.exports = {
  createUser: async function({ userInput }, req) {
    //   const email = args.userInput.email;
    const existingUser = await User.findOne({ email: userInput.email });
    if (existingUser) {
      const error = new Error('User exists already!');
      throw error;
    }
    const hashedPw = await bcrypt.hash(userInput.password, 12);
    const user = new User({
      email: userInput.email,
      name: userInput.name,
      password: hashedPw
    });
    const createdUser = await user.save();
    return { ...createdUser._doc, _id: createdUser._id.toString() };
  }
};

在使用 graphiql 工具的浏览器中,我正在输入以下代码进行测试:

mutation {
  createUser(userInput: {email: "test@test.com", name: "test", password: "123456"}) {
    _id
    email
  }
}

但是,这向我显示了此错误, “无法为非空字段RootMutation.createUser返回null。” 讲师的模拟效果很好。但是给我这个错误。

0 个答案:

没有答案