简体   繁体   中英

How to delete embedded (nested) document using node.js in mongodb

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM