【发布时间】:2020-11-15 12:19:38
【问题描述】:
我有这些类型和查询:
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]!
}
这就是它们在我的 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",
}
);
问题出在作者
基本上,每当我创建一个帖子时,作者字段都会保存为一个字符串,它是对用户 ID 的引用。一切都很好,直到我必须在前端进行查询:
export const GET_ALL_POSTS = gql`
query {
getAllPosts {
picture
id
description
createdAt
likes
author {
id
}
}
}
`;
问题是在数据库中,作者被保存为字符串,即使在我的 Mongoose 中我尝试将其保存为 ObjectID 引用。因此,当我进行查询并且想要“作者”时,我不能只查询“作者”,因为在我的 typedefs 中,作者是一个对象并且它需要一个子字段(它不起作用,因为在我的数据库作者是一个字符串),如果我尝试像字符串一样查询它,我不能,因为 GraphQL 认为作者是一个带有子字段的对象。
有什么办法解决吗?
【问题讨论】:
标签: javascript reactjs mongoose graphql