0

I have this line of code

    const comments = await db.Comment.find({post: req.params.post_id});
    return res.status(200).json({comments});

The request is being sent to the back-end successfully but the comments response is an empty array

/*
  res code: 200
*/

{
 comments: []
}

I checked other DB functions and they all work fine like adding a comment, editing it etc

my comment collection looks like this

{"_id":{"$oid":"605d1faeb202e4425c004be9"},"text":"Welcome to this comment","user":{"$oid":"5ff5d878dd830142686b7fd5"},"post":{"$oid":"6016f770ea76030d24688f89"},"createdAt":{"$date":{"$numberLong":"1616715694247"}},"updatedAt":{"$date":{"$numberLong":"1616715694247"}},"__v":{"$numberInt":"0"}}


--------------------------------------------------------
{"_id":{"$oid":"605d1fb8b202e4425c004bea"},"text":"Welcome to this comment2","user":{"$oid":"5ff5d878dd830142686b7fd5"},"post":{"$oid":"6016f770ea76030d24688f89"},"createdAt":{"$date":{"$numberLong":"1616715704381"}},"updatedAt":{"$date":{"$numberLong":"1616715704381"}},"__v":{"$numberInt":"0"}}

I am trying to search by post id which is saved as post in my comment Collection

Ahmed Gaafer
  • 1,603
  • 9
  • 26
  • 2
    `req.params.post_id` is a string, the `post` field is an ObjectId. See [Mongoose String to ObjectID](https://stackoverflow.com/questions/38446346/mongoose-string-to-objectid) – Joe Mar 26 '21 at 00:27

1 Answers1

1

I think you need to wrap req.params.post_id in ObjectId.

Like this

const ObjectId = require('mongoose').Types.ObjectId;

const comments = await db.Comment.find({
   post: new ObjectId(req.params.post_id)
});
fortunee
  • 3,852
  • 2
  • 17
  • 29