node.js - 如何使用expressjs在mongoDB的嵌套数组中只删除一个对象元素?
问题描述
我正在尝试以下代码来删除评论。所以我想要的是,每当我点击删除相应评论时,它都应该被删除。但是我在这里面临的问题是,无论单击任何删除按钮,它都会删除所有评论。为什么会这样?
删除评论的路由代码。
router.route("/deleteComment").get(function(req, res) {
console.log("AddtasksId = "+req.query.AddtasksId + "id = "+req.query.id);
Comments.findOneAndUpdate({'AddtasksMain.AddtasksId':req.query.AddtasksId},
{$pull: {"AddtasksMain.$.comments":{"_id": req.query.id}}},
function(err, deleteComments) {
if(deleteComments) {
console.log("Comment deleted!")
return res.end('{"msg" : "Comment Deleted", "status" : 200}');
}
else {
return res.end('{"msg" : "Comment not Deleted", "status" : 300}');
}
});
});
AJAX 调用:
$(document).on("click", ".deleteComments", function() {
var id = $(this).prop("id");
var AddtasksId = $('#submitBtn4comment').attr('data-taskId');
$.ajax({
type: "GET",
url: "/deleteComment",
dataType: "json",
data: {
AddtasksId: AddtasksId,
id:id
},
contentType: "application/json",
success: function(response){
if(response.status == 200)
window.location.reload();
}
});
})
评论架构:
{
"AddtasksId" : "cxlq2iqy85qy$s",
"_id" : ObjectId("5fcd1ca940542e29c0b4b0c7"),
"comments" : [
{
"commentDate" : "Dec 7 2020 at 0:14",
"comment" : "Closing it now.",
"username" : "Michael Con",
"_id" : ObjectId("5fcd268e40542e29c0b4b0d9")
},
{
"commentDate" : "Dec 9 2020 at 0:14",
"comment" : "Close it now.",
"username" : "Ricky K",
"_id" : ObjectId("5fcd268e40586e29c1b4b0r7")
}
]
}
我只想通过_id:5fcd268e40586e29c1b4b0r7
单击删除锚文本来删除假设只有第二条评论。但不是删除一条评论,而是删除所有评论。请告诉我发生了什么事?
更新:
var commentSchema = new mongoose.Schema({
ClientId: {
type: String,
unique: true
},
AddtasksMain : [{
AddtasksId: String,
comments: [
{
username: String,
comment: String,
commentDate:String
}
]
}]
});
解决方案
我只是将其更改findOneUpdateOne
为UpdateMany
并且有效。这是解决方案UpdateMany
:
router.route("/deleteComment").get(function(req, res) {
console.log("AddtasksId = "+req.query.AddtasksId + "id = "+req.query.id);
Comments.updateMany({'AddtasksMain.AddtasksId':req.query.AddtasksId},
{$pull: {"AddtasksMain.$.comments":{"_id": req.query.id}}},
function(err, deleteComments) {
if(deleteComments) {
console.log("Comment deleted!")
return res.end('{"msg" : "Comment Deleted", "status" : 200}');
}
else {
return res.end('{"msg" : "Comment not Deleted", "status" : 300}');
}
});
});
推荐阅读
- css - 您可以在 sass 中选择样式元素的当前状态吗?
- llvm - 无法在 Ubuntu 16.04 上安装 llvm-9 或 clang-9
- xcode - SwiftUI:用字典定义搜索结果列表的困难
- c++ - 为什么括号在这个简单的代码中有所不同
- axon - 应用事件后,聚合标识符必须为非空。确保聚合标识符最迟初始化
- r - 加入空数据帧时忽略/抑制错误
- mongodb - 无法从其他服务连接到 mongodb 服务
- ruby - Rspec:没有这样的文件或目录@rb_sysopen -
- javascript - 使用 selenium js 连接到已经启动的 Web 驱动程序
- python - 在熊猫中按列 dtype 进行 if-else