0

I currently have three Mongoose models.

Post

const schema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    desc: {
      type: String,
      required: true,
    },
    content: {
      type: String,
      required: true,
    },
    slug: {
      type: String,
      required: true,
    },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
  },
  { timestamps: true }
);

Comment

const schema = new mongoose.Schema(
  {
    content: {
      type: String,
      required: true,
    },
    user: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref: 'User',
    },
  },
  { timestamps: true }
);

User

const schema = new mongoose.Schema(
  {
    handle: {
      type: String,
      required: true,
    },
    thumbnail: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

When I query a specific Post in my Manager class with:

static async getPost(slug: string) {
  return await BlogPostModel.findOne({ slug }).populate('comments');
}

I successfully get back a JSON response with the following:

{
    "_id": "6176d19b1aecee2189bf458d",
    "title": "My New Blog Post",
    "desc": "This is going to be a post about my newest blog post",
    "content": "Lorem ipsum",
    "slug": "my-new-blog-post",
    "comments": [
        {
            "_id": "6176d701b3b8d00a7042a4d6",
            "content": "What an amazing comment this is.",
            "user": "6176c5d0bec3c2b694c9a48e",
            "createdAt": "2021-10-25T16:10:41.619Z",
            "updatedAt": "2021-10-25T16:10:41.619Z",
            "__v": 0
        },
        {
          "_id": "6176d701b3b8d00a7042a4d6",
          "content": "Second best comment.",
          "user": "6176c5d0bec3c2b694b9a47f",
          "createdAt": "2021-10-25T16:10:41.619Z",
          "updatedAt": "2021-10-25T16:10:41.619Z",
          "__v": 0
      },
    ],
    "createdAt": "2021-10-25T15:47:39.160Z",
    "updatedAt": "2021-10-25T16:10:41.657Z",
    "__v": 2
}

My question is, how would I go about populating the user data in each comment, instead of just the object id being there?

Dan Zuzevich
  • 3,002
  • 2
  • 20
  • 36

0 Answers0