问题描述
我知道这是一个比较常见的问题,但我的实现与其他帖子不同.我正在使用我无法开始工作的最基本的实现.我使用 Sequelize 和 MySQL 作为数据库实现.
I know this is a somewhat common issue, but my implementation differs from the other posts. I'm using the most basic implementation which I can't get to work. I'm using Sequelize with MySQL as the database implementation.
resolvers.js
resolvers.js
const resolvers = {
Query: {
async getStudent (root, { id }, { models }) {
return models.User.findByPk(id)
},
},
Mutation: {
async createUser (root, { name, email }, { models }) {
return models.User.create({
name,
email
})
},
},
}
schema.js
const { gql } = require('apollo-server-express');
const typeDefs = gql`
type User {
id: Int!
name: String!
email: String!
}
type Query {
getUser(id: Int!): User
getAllUsers: [User!]!
}
type Mutation {
createUser(name: String!, email: String!): User!
}`
module.exports = typeDefs;
用户模型
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
name: DataTypes.STRING,
email: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
return User;
};
然而,当运行以下突变时:
Yet when running the following mutation:
mutation{ createUser(name:"Nate", email:"[email protected]"){id } }
我收到:
错误":[{"message": "不能为不可为空的字段 Mutation.createUser 返回空值.",地点":[{线":2,列":3}],小路": [创建用户"],
推荐答案
就我而言,这是因为 createUser 调用不是异步的.希望这对某人有所帮助:
In my case it was because the createUser call was not asynchronous. Hopefully this helps someone:
return await models.User.create({
name,
email
})
这篇关于Apollo GraphQL“无法为不可为空的字段 Mutation.createUser 返回 null";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!