1

here is my schema...

 const commentSchema = new mongoose.Schema({
      comment: String,
      imagename:String
    });
    const Comment  =  new mongoose.model("Comment",commentSchema);



    const userSchema = new mongoose.Schema({
      email: String,
      password:String,
      comments: [commentSchema]

    });
    userSchema.plugin(passportLocalMongoose);
    const User = new mongoose.model("User", userSchema);

I am trying to delete an embedded document using ...

  app.post("/delete", function(req,res){
      if(req.isAuthenticated()) {
        User.findById(req.user.id,function(err, foundUser){
          if(err){
            console.log(err);
          }
          else{
            const uid = foundUser.id;                 //this is the User iD
         const checkedItemId = (req.body.checkbox);  //this is the comment ID
         console.log(checkedItemId);

    User.updateOne(_id:"uid","comments._id": checkedItemId},{$pull :{comments:{_id :checkedItemId}}});
     User.Comment.pull(checkedItemId);
            if(!err){
              console.log("successfully deleted");
     res.redirect("data")

            }

       }
       });
    }
    else{
     res.redirect("/");
    }
    });

>I want to delete a comment: hello and image associated.

"_id" : ObjectId("5eb798bb64d8f94df08a6ae7"), 
    "username" : "random", 
    "comments" : [
        {
            "_id" : ObjectId("5eb798cd64d8f94df08a6ae8"), 
            "comment" : "hello", 
            "imagename" : "image-1589090509389.jpeg"
        }
    ]

I am trying to delete a selected comment in a user, when the user clicks on the button on ejs page. it automatically generates that comment id, and user id is generated using authentication. so using comment id and user id, how can I delete a comment in MongoDB using node.js. I tried updateOne and pull, but it's not working.

EDIT: After this question I got to know that there are 2 ways to solve this question, one is embedded and the other is a reference.
previously all the answers were dependent on the embedded model in the schema, and this question works on the reference model.
Riyazat Durrani
  • 588
  • 1
  • 8
  • 20
  • If one of the answers below answered your question, the way this site works works, you'd "accept" and "upvote" the answer, more here: [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers). But only if your question really has been answered. If not, consider adding more details to the question – Puneet Singh May 10 '20 at 10:24
  • This should answer your question [Remove embedded document in a nested array of documents](https://stackoverflow.com/questions/10950451/remove-embedded-document-in-a-nested-array-of-documents) Make sure you search before you post questions. – aldokkani May 10 '20 at 10:52
  • Does this answer your question? [Remove embedded document in a nested array of documents](https://stackoverflow.com/questions/10950451/remove-embedded-document-in-a-nested-array-of-documents) – aldokkani May 10 '20 at 10:52
  • Thanks for the feedback! Votes cast by those with less than 15 reputations are recorded, but do not change the publicly displayed post score.@PuneetSingh. – Riyazat Durrani May 10 '20 at 10:55
  • I had checked that reply of yours @aldokkani but I guess he has done with the reference method, and my code worlds on an embedded method, didn't know about mongoose.Types.ObjectId(req.body.checkbox) before. – Riyazat Durrani May 10 '20 at 11:03

1 Answers1

2

You are passing comment _id and user _id as a string in the query which will not work, you need to convert that into ObjectId, Please check updated code below

var mongoose = require('mongoose');

app.post("/delete", function(req,res){
  if(req.isAuthenticated()) {
    User.findById(req.user.id,function(err, foundUser){
      if(err){
        console.log(err);
      }
      else{
        const uid = foundUser.id;                 //this is the User iD
        const checkedItemId = mongoose.Types.ObjectId(req.body.checkbox);  //this is the comment ID
        console.log(checkedItemId);

        User.updateOne({_id: uid},{$pull :{comments:{_id :checkedItemId}}}, function(err, results){
          if(!err){
            console.log("successfully deleted");
            res.redirect("data")
          } else {
            console.log("error in deletion");
            res.redirect("/");
          }
        });
      }
    });
  } else {
    res.redirect("/");
  }
});

In the above code, You are getting user_id in ObjecId format from findbyId function, just don't put "" on it, and converted the comment _id in ObjectId format

Puneet Singh
  • 3,477
  • 1
  • 26
  • 39
  • Hi bhai,I was trying to search u all over..I have a doubt if u can figure it out.. https://stackoverflow.com/questions/61928748/find-nested-embedded-object-in-the-collection/61928880?noredirect=1#comment109532942_61928880 – Riyazat Durrani May 21 '20 at 07:35
  • User.findById this is extra call you can do it the same without 'User.findById' .. use this in your inner query mongoose.Types.ObjectId(req.user.id) – Khurram Ali May 22 '21 at 20:06