首页 > 解决方案 > GraphQL 和 mongoose 在验证用户时返回 nulll

问题描述

我正在为用户使用 mongoose 和 graphql 实现登录功能,但是我从登录解析器中得到了 null 。这是模型:

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const userSchema = new Schema({
    username: { type: String, unique: true, required: true, trim: true },
    email: { type: String, unique: true, required: true, trim: true },
    password: { type: String, required: true },
    phone: { type: String, unique:true, required: true, trim: true },
    emailVerified: { type: Boolean, default: false },
    phoneVerified: { type: Boolean, default: false }
})

module.exports = mongoose.model('User', userSchema)

我正在使用电子邮件和密码登录,我尝试注册用户并且它有效。

在 graphql 结束时,我有 2 个模式,UserType 和 ActiveUserType,ActiveUserType 返回用户登录的 jwt 令牌:

const ActiveUserType = new GraphQLObjectType({
    name: 'ActiveUser',
    fields: () => ({
        success: { type: GraphQLBoolean },
        message: { type: GraphQLString },
        token: { type: GraphQLString },
        username: { type: GraphQLString }
    })
})

然后我在 rootquery 中创建一个登录字段:

login: {
        type: ActiveUserType,
        args: { email: { type: new GraphQLNonNull(GraphQLString) }, password: { type: new GraphQLNonNull(GraphQLString) } },
        resolve: function(parent, args) {
            return User.findOne({ email: args.email, password: args.password }, function(err, user) {
                if(err) {
                    return {
                        success: false,
                        message: "an error occurred",
                        token: null,
                        username: null
                    }
                }

                if(!user) {
                    return {
                        success: false,
                        message: "user not found"
                        token: null,
                        username: null
                    }
                }

                return {
                    success: true,
                    token: "something",
                    username: user.username
                }

            })
        }

    },

但是,当我使用集合中肯定存在的电子邮件和密码请求 graphiql 前端的登录字段时,我得到输出:

{
  "data": {
    "login": null
  }
}

这是我第一次尝试使用 mongoose 和 graphql,因此无法推断出这里出了什么问题,但是在发布这个问题之前已经研究了几个线程,但没有找到任何解决方案。非常感谢您的帮助。

标签: javascriptnode.jsmongodbmongoosegraphql

解决方案


推荐阅读