【发布时间】:2021-10-07 09:24:39
【问题描述】:
到目前为止,除了这个之外,所有测试过的查询和突变都可以正常工作。
我在阿波罗游乐场收到此错误。
“消息”:
Cannot return null for non-nullable field Mutation.createComment
...
“扩展”:
...
Data: null
如果不是所有我能找到的 google 和 stackoverflow 解决方案,我已经尝试了大部分,现在我正在寻求帮助。非常感谢我能得到解决此问题的任何帮助。
后模型:
const postSchema = new Schema({
body: String,
username: String,
createdAt: String,
comments: [
{
body: String,
username: String,
createdAt: String,
},
],
likes: [
{
username: String,
createdAt: String,
},
],
// Linking the user model
user: {
type: Schema.Types.ObjectId,
ref: "users",
},
});
评论解析器:
Mutation: {
createComment: async (_, { postId, body, username }, context) => {
const { username } = checkAuth(context);
if (body.trim === "") {
throw new UserInputError("Empty comment", {
errors: {
body: "Comment body can not be empty",
},
});
}
const post = await Post.findById(postId);
if (post) {
post.comments.unshift({
body,
username,
createdAt: new Date().toISOString(),
});
await post.save();
return post;
} else throw new UserInputError("Post not found");
},
类型定义:
type Post {
id: ID!
body: String!
createdAt: String!
username: String!
comments: [Comment]!
likes: [Like]!
likeCount: Int!
commentCount: Int!
}
type Comment {
id: ID!
createdAt: String!
username: String!
body: String!
}
type Like {
id: ID!
createdAt: String!
username: String!
}
type User {
id: ID!
email: String!
token: String!
username: String!
createdAt: String!
confirmed: Boolean!
}
input RegisterInput {
username: String!
password: String!
confirmPassword: String!
email: String!
}
type Query {
getUsers: [User]
getPosts: [Post]
getPost(postId: ID!): Post
}
type Mutation {
register(registerInput: RegisterInput): User!
login(email: String!, password: String!): User!
createPost(body: String!): Post!
deletePost(postId: ID!): String!
createComment(postId: ID!, body: String!, username: String!): Post!
deleteComment(postId: ID!, commentId: ID!): Post!
likePost(postId: ID!): Post!
}
type Subscription {
newPost: Post!
}
我在 Apollo Playground 中使用的变异:
mutation createComment{
createComment(
postId: "6106db3a0e9e783e98b996a4",
body: "This is a new comment",
username: "Random user"
) {
id
comments {
id
body
createdAt
username
}
commentCount
}
}
【问题讨论】:
标签: graphql apollo-server