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.