我正在将 MongoDB 与 Mongoose 和 GraphQL 一起用于类项目。我遇到了一个问题,即 GraphQL 在嵌套文档引用中的字段上返回 null(引用用户模式的 postedBy)。我希望这些字段由引用的对象数据填充,但只返回 ID。
模型
const postSchema = new Schema(
{
postText: {
type: String,
required: 'You need add text to your post',
minlength: 1,
maxlength: 10000,
},
createdAt:{
type: Date,
default: Date.now,
get: createdAtVal => dateFormat(createdAtVal)
},
postedBy: {
type: Schema.Types.ObjectId, ref: "User",
required: true
},
comments: [commentSchema]
},
{
toJSON: {
virtuals: true,
getters: true
},
}
)
postSchema.virtual('commentCount').get(function() {
return this.comments.length;
});
const Post = model('Post', postSchema);
module.exports = Post;
类型定义
type Post {
_id: ID
postText: String
createdAt: String
postedBy: User
comments: [Comment]
commentCount: Int
}
解析器
addPost: async (parent, args, context) => {
if (context.user) {
const post = await Post.create({ ...args, postedBy: context.user._id });
await User.findByIdAndUpdate(
{ _id: context.user._id },
{ $push: { posts: post._id } },
{ new: true }
);
return post;
}
throw new AuthenticationError('You need to be logged in!');
}
我能够成功查询帖子并使用用户的_id、用户名和图像(url)填充引用的字段。当我运行突变时,用户名和图像返回 null。
这是我的突变:
mutation addPost($PostText: String!) {
addPost(postText: $postText) {
_id
postText
createdAt
postedBy {
_id
username
image
}
commentCount
comments {
_id
}
}
}
这是它得到的响应:
{
"data": {
"addPost": {
"_id": "60612871bd89e52ca08d3ea1",
"postText": "This is an example of a post.",
"createdAt": "Mar 28th, 2021 at 21:08 pm",
"postedBy": {
"_id": "6060a868d856f01738f45185",
"username": null,
"image": null
},
"commentCount": 0,
"comments": []
}
}
}
我究竟做错了什么?