GraphQL 嵌套文档在突变时返回 null

问题描述

我正在将 MongoDB 与 Mongoose 和 GraphQL 一起用于课堂项目。我遇到了一个问题,GraphQL 在嵌套文档引用(引用用户架构的 postedBy)中的字段上返回 null。我希望这些字段由引用的对象数据填充,但只返回 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": []
    }
  }
}

我做错了什么?

解决方法

由于您只获得了 ref 而没有其他数据,我认为您只是忘记填充用户字段。

试试:

return await post.populate('postedBy').execPopulate();