为什么graphql返回“无法返回不可为空的字段mutation.createAccnt的null”

时间:2020-04-27 12:40:48

标签: javascript graphql

我正在通过此突变createaccnt为新用户创建帐户,但是最终我还是得到了上面的错误,已经盯着它几天了。有人可以指出我的混乱和纠正之处。 这是代码。 我如何定义架构

const userSchema = new Schema({
    username:String,
    email:String,
    Password:String,
    addedOn:String

});

类型定义

//user type definitio

type User{
    id:ID!,
    username:String!,
    email:String!,
    token:String!,
    Password:String!,
    addedOn:String!,

},
input UserInput{
  email:String!,
  username:String!,
  Password:String!,
  confirmPassword:String!
},
//mutation
type Mutation{
    createAccnt ( userInput:UserInput!) : User!
      }
这就是我实施mutatiion

的方式

//createAccnt 
async createAccnt(parent,{userInput:{
            email,
            username,
            Password,
            confirmPassword
        }},context,info){
            try {
                const {errors,valid}=validateUserInput(
                    email,
                    username,
                    Password,
                    confirmPassword
                );
                //allow for error detection
                if(!valid){
                    throw new UserInputError('errors',{errors})
                };
                //check if user already exist
                const user= await User.findOne({username});
                if(user){
                    throw new UserInputError('username is taken',{
                        errors:{
                            username: 'username is taken'
                        }
                    });
                };
                //hash password
                Password= await bcrypt.hash(Password,12);
                //create a new user object
                const newUsr= new User({
                    email,
                    username,
                    Password,
                    addedOn:new Date().toISOString()
                });

                //save to db
                const res=await newUsr.save();
                //web token
                const token= jwt.sign({
                    id:res.id,
                    email:res.email,
                    usernaem:res.username
                },SECRET_KEY,{expiresIn:'1h'});


                return{
                    ...res._doc,
                    id:res._id,
                    token
                }
            }
             catch (error) {
                throw new Error(error)
            }

我已通过代码彻底检查,无法识别错误。请在可能的情况下帮助识别和更正。

1 个答案:

答案 0 :(得分:0)

如果不确定引擎盖下的处理方式。

type User{
    id:ID!,
    username:String!,
    email:String!,
    token:String!,
    Password:String!,
    addedOn:String!,

}

”!这意味着不能返回“ null”,因此请确保您的代码正确返回了User 在上面,这意味着您必须必须返回这样的User对象。

return {
    id: "some id here",
    username: "some username here",
    email: "some email here",
    token:"token here",
    Password:"pass here",
    addedOn: "date here",

}