mongodb - Graphql 的登录突变未找到用户
问题描述
我正在尝试使用 graphql 和 mongodb 创建身份验证服务。我已经创建了我的登录突变,它接受了电子邮件和密码。我正在使用 bcrypt 来散列和取消散列密码。
这不是导入问题或 mongodb 问题,而是 graphql。
const UserType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: {type: GraphQLID},
username: {type: GraphQLString},
email: {type: GraphQLString},
password: {type: GraphQLString},
institution: {
type: InstitutionType,
resolve(parent, args){
return Institution.findById(parent.institutionId)
}
}
})
});
login:{
type:GraphQLString,
args:{
email: {type: GraphQLString},
password: {type: GraphQLString}
},
resolve: async (parent, { email, password }, { models, SECRET }) => {
const user = await models.User.findOne({ where: { email } });
if (!user) {
throw new Error('No user with that email');
}
const valid = await bcrypt.compare(password, user.password);
if (!valid) {
throw new Error('Incorrect password');
}
const token = jwt.sign(
{
user: _.pick(user, ['id', 'username']),
},
SECRET,
{
expiresIn: '1y',
},
);
return token;
},
},
}});
它应该返回一个 jwt 令牌,以后可以用于身份验证。首先,我在浏览器的 graphiql 中运行它:
mutation{
login(email: "ammarthayani@gmail.com", password:"password"){
}
}
它在控制台中给了我这个:“语法错误:预期名称,找到
然后我尝试了:
mutation{
login(email: "ammarthayani@gmail.com", password:"password"){
username
}
}
这给了我:字段 \"login\" 不能有选择,因为类型 \"String\" 没有子字段。
解决方案
类型上login
字段的Mutation
类型是GraphQLString
,它是一个标量。由于标量是叶节点,它们没有选择集(即其他“子”字段)。从规格:
如果 selectionType 是标量或枚举:
- 该选择的子选择集必须为空
如果 selectionType 是接口、联合或对象
- 该选择的子选择集不得为空
花括号用于指示选择集,因此当字段的返回类型是标量或枚举时,不应使用它们。您的查询需要简单的是:
mutation {
login(email: "ammarthayani@gmail.com", password:"password")
}
推荐阅读
- javascript - 获取登录我的应用程序的所有用户的列表并将其记录在我的数据库中
- python - 检查熊猫系列是否包含给定值时,“in”运算符无法按预期工作
- angular6 - Angular 2 复选框验证
- python - 如何在一个文件python脚本中将函数分配给其他函数?
- php - Laravel 表单提交没有走正确的路线?
- javascript - 在本地运行节点与在 Web 服务器上安装节点不同吗?
- android - 使用 Android NDK 演示 printf 或 __android_log_print 漏洞
- python - 使用终端安装python时遇到问题
- ios - In App Purchase (validation) Receipt receiptStatus 为 nil
- html - 将特殊字符限制在输入框中