这是我的图式...
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);
我正在尝试使用...删除嵌入式文档
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("/");
}
});
>我要删除评论:您好和图片相关。
"_id" : ObjectId("5eb798bb64d8f94df08a6ae7"),
"username" : "random",
"comments" : [
{
"_id" : ObjectId("5eb798cd64d8f94df08a6ae8"),
"comment" : "hello",
"imagename" : "image-1589090509389.jpeg"
}
]
当用户单击ejs页面上的按钮时,我试图删除用户中的选定评论。它会自动生成该注释ID,并使用身份验证生成用户ID。因此,使用注释ID和用户ID,如何使用node.js在MongoDB中删除注释。我尝试了updateOne并拉出,但是它不起作用。
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.
您在查询中将注释_id和用户_id作为字符串传递,将无法使用,您需要将其转换为ObjectId,请检查下面的更新代码
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("/");
}
});
在上面的代码中,您正在从findbyId函数获取ObjecId格式的user_id,只是不要在其上加上“”,而将注释_id转换为ObjectId格式
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句