Search code examples
mongodbmongoose

How to find mongoose parent doc by subdoc id?


I'm making a React application where I have comments section. On my node.js backend I have a mongoose model of 'comment' that has replies array field where it might have another 'comment' objects of the same type. And I'm trying to make main comment to have replies nested only one level (like youtube, not like reddit).

My mongoose model looks like this.

const commentSchema = new Schema({
  body: {
    type: String,
    required: true
  },
  likes: {
    type: Number,
    default: 0,
  },
  wroteBy: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  replies: [this]
}, { timestamps: true })

So whenever I make a request from front-end I'm passing commentId to the request data object. I'm trying to find if the parent exists for provided id so I can push the new comment to the replies of that parent (main) comment, if there is no parent found it means that I'm replying to the main comment and I will just push new comment to that id.

I tried retrieving parent doc with the following code mentioned in the other stackoverflow post.

Comment.find({"replies._id": commentId})

but it always returns an empty array.


Solution

  • Make sure you're querying by ObjectId not string.

    const { ObjectId } = require('mongodb');
    
    Comment.find({ "replies._id": new ObjectId(commentId) })
    

    To ensure good performance make sure you have relevant index ({ "replies._id": 1 }).