1

I found this answer thinking it solved my problem until I realized that the query returns the whole parent document.

Is there anyway to query for, and edit only, a specific element in a subarray in a document?

So it'd go something like,

const newComment = {...};

const comment = await Post.find({comments: ObjectId("50ae3bdb50b3d6f014000279")})

comment.push(newComment);

await comment.save();

The reason I want to accomplish this is because comments are nested within the Post schema. It'd be more efficient if I can have the comment returned, specified with the comment ID, and cycle through all the likes of that comment. Instead of cycling through all the comments of the Post, and then cycling through all the likes.

Mike K
  • 7,621
  • 14
  • 60
  • 120

1 Answers1

0

You can use the following approach ,

const newComment = {...};

Post.find( { "comments": "50ae3bdb50b3d6f014000279" } )
.exec((err , foundComment) => {
   if(err){
      console.log(err)
   }else{
     foundComment.push(newComment);
     foundComment.save();
   }

});
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43