【问题标题】:run mutation to store new user's post return Error: Variable '$data' expected value of type运行突变以存储新用户的帖子返回错误:变量“$data”类型的预期值
【发布时间】:2026-02-23 23:30:01
【问题描述】:

我使用 graphql-yoga 和 prisma 创建了用户和发布数据模型。一个用户可以有很多帖子 我确实喜欢下面。现在根据addPost 突变,我想添加与当前用户相关的新帖子。但是graphql服务器返回以下错误

但是当我运行突变时:

mutation {
  addPost(title:"aa", body: "bb"){
    id
    title
    author {
      id
      email
    }
  }
}

给我这个错误:为什么会这样?我该如何解决这个问题?

  "errors": [
    {
      "message": "Error: Variable '$data' expected value of type 'PostCreateInput!' but got: {\"title\":\"aa\",\"body\":\"bb\",\"author\":{\"id\":\"5f036dc924aa9a00070c4771\",\"email\":\"bb@bb.com\"}}. Reason: 'author.id' Field 'id' is not defined in the input type 'UserCreateOneInput'. (line 1, column 11):\nmutation ($data: PostCreateInput!)

数据模型.prisma

type User {
  id: ID! @id
  email: String! @unique
  password: String!

}

type Post {
  id: ID! @id
  title: String!
  body: String!
  author_id: Int
  author:     User!   @relation(link: INLINE,fields: [authorId], references: [id])
  createdAt: DateTime @createdAt
  updatedAt: DateTime @updatedAt
}

架构:

type User {
    id: ID!
    email: String!
}

type Post {
    id: ID!
    title: String!
    body: String!
    author: User!
}

input UserInput {
    id: ID!
    email: String!
}

type Mutation {
    addPost(title: String!, body: String!) : Post!
}

解析器。

   addPost: async (parent, { title, body }, { prisma, me }) => {
      console.log(me);
      try {
        const post = await prisma.createPost({
          title,
          body,
          author: {id: me.user.id, email: me.user.email}
        });
        return post;

      } catch (error) {
        throw new Error(error);

      }
    }

【问题讨论】:

    标签: graphql prisma express-graphql prisma-graphql


    【解决方案1】:

    应该是:

    const post = await prisma.createPost({
      title,
      body,
      author: {
        connect: { id: me.user.id, email: me.user.email }
      }
    });
    

    这会将帖子添加到现有用户。

    另外,如果您开始使用 Prisma,我会推荐 Prisma 2

    【讨论】:

    • 谢谢,我稍后会尝试 prisma 2。我确实喜欢你,但我有新错误:"Error: You provided more than one field for the unique selector on User. If you want that behavior you can use the many query and combine fields with AND / OR
    • 只需使用 id 或电子邮件。不要同时使用两者。一个唯一标识符就足够了
    最近更新 更多