简体   繁体   English

GraphQL 类型与 ZCCADCDEDB567ABAE643E15DCF0974E503Z 架构不匹配

[英]GraphQL Type doesn't match Mongoose schema

I have these types and query:我有这些类型和查询:

type Post {
    id: ID!
    author: User!
    description: String!
    createdAt: String!
    picture: String!
    likes: Int!
    comments: [Comment]!
}

type User {
    id: ID!
    email: String!
    password: String!
    name: String!
    username: String!
    createdAt: String!
    age: Int!
    posts: [Post]!
    comments: [Comment]!
    images: [Image]!
    followers: [Follower]!
    following: [Following]!
}

And this is how they are linked in my Mongoose Schema / MongoDB:这就是它们在我的 Mongoose Schema / MongoDB 中的链接方式:

const postSchema = new Schema(
  {
    _id: {
      type: String,
      required: true,
      auto: false,
    },
    description: {
      type: String,
      required: true,
    },
    picture: {
      type: String,
      required: true,
    },
    author: {
      type: mongoose.Types.ObjectId,
      ref: "User",
      required: true,
    },
    createdAt: {
      type: String,
      required: true,
    },
    likes: {
      type: Number,
      required: true,
    },
    comments: [
      {
        type: mongoose.Types.ObjectId,
        ref: "Comment",
      },
    ],
  },
  {
    collection: "Posts",
  }
);

The problem is at author问题出在作者身上

Basically, whenever I create a Post, the author field is saved as a string that is a reference to a User ID.基本上,每当我创建一个帖子时,作者字段都会保存为一个引用用户 ID 的字符串。 All good until I have to make a query on the frontend:一切都很好,直到我必须在前端进行查询:

export const GET_ALL_POSTS = gql`
  query {
    getAllPosts {
      picture
      id
      description
      createdAt
      likes
      author {
        id
      }
    }
  }
`;

The problem is that in the database, author is saved as a String even though in my Mongoose I try to save it as a ObjectID reference.问题是在数据库中,作者被保存为字符串,即使在我的 Mongoose 中我尝试将其保存为 ObjectID 引用。 So, when I do my query and I want the 'author', I can't query just the 'author' because in my typedefs, the author is an Object and it requires a subfield (which it doesn't work because in my database the author is a string) and if I try to query it just as String, I can't because GraphQL thinks that author is an object with subfields.因此,当我进行查询并且我想要“作者”时,我不能只查询“作者”,因为在我的 typedef 中,作者是 Object 并且它需要一个子字段(它不起作用,因为在我的数据库作者是一个字符串),如果我尝试将它作为字符串查询,我不能,因为 GraphQL 认为作者是一个带有子字段的 object。

Any way to deal with this?有什么办法处理这个吗?

Answer:回答:

Mongoose has an option populate that you can use to call an object by it's id inside another object. Mongoose 有一个选项填充,您可以使用它在另一个 object 中通过它的 id 调用 object。 All in one call.一次通话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM