Craig5117
Craig5117

Reputation: 55

GraphQL nested document returns null on mutation

I am using MongoDB with Mongoose and GraphQL for a class project. I am stuck on an issue with GraphQL returning null on fields within a nested document reference (postedBy which references the User schema). I expect the fields to be populated by the referenced object data, but only the ID returns.

Model

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
}

Resolver

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

I am able to successfully query the post and have the referenced field populated with the user's _id, username, and image(url). When I run the mutation, the username and image return null.

Here is my mutation:

mutation addPost($PostText: String!) {
    addPost(postText: $postText) {
      _id
      postText
      createdAt
      postedBy {
        _id
        username
        image
      }
      commentCount
      comments {
        _id
      }
    }
  }

And here is the response it gets:

{
  "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": []
    }
  }
}

What am I doing wrong?

Upvotes: 1

Views: 670

Answers (1)

minefield_tester
minefield_tester

Reputation: 103

Since you're only getting the ref and no additional data, I think you just forgot to populate the user field.

Try:

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

Upvotes: 2

Related Questions