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.
5
  • 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?. But only if your question really has been answered. If not, consider adding more details to the question Commented May 10, 2020 at 10:24
  • This should answer your question Remove embedded document in a nested array of documents Make sure you search before you post questions. Commented May 10, 2020 at 10:52
  • Does this answer your question? Remove embedded document in a nested array of documents Commented May 10, 2020 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. Commented May 10, 2020 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. Commented May 10, 2020 at 11:03

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi bhai,I was trying to search u all over..I have a doubt if u can figure it out.. stackoverflow.com/questions/61928748/…
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.