GraphQL 嵌套文档 returns 突变时为 null

GraphQL nested document returns null on mutation

我正在将 MongoDB 与 Mongoose 和 GraphQL 一起用于 class 项目。我在嵌套文档引用(postedBy 引用用户模式)中的字段上遇到 GraphQL returning null 的问题。我希望字段由引用的对象数据填充,但只有 ID returns.

型号

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;

TypeDef

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!');
          }

我能够成功查询 post 并在引用字段中填充用户的 _id、用户名和图像 (url)。当我运行突变时,用户名和图像return 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();