Reputation: 376
I want to remove object using its id, I don't want MongoDB query I just want to remove object using its id, array stored in the variable, we can use the javascript function aswell
Example
If I pass id=ObjectId("5b693e7ddd65ec16a46b7f82")
from this object
[{
"commentedBy": "test",
"subComments": {
"commentedBy": "jaril 2",
"subComments": {
"commentedBy": "jaril 3",
"subComments": {
"commentedBy": "jaril 4",
"commentId": ObjectId("5b693e7ddd65ec16a46b7f85")
},
"commentId": ObjectId("5b693e7ddd65ec16a46b7f84")
},
"commentId": ObjectId("5b693e7ddd65ec16a46b7f83")
},
"commentId": ObjectId("5b693e7ddd65ec16a46b7f82")
}]
then output should like this
[]
or if i pass id=ObjectId("5b693e7ddd65ec16a46b7f83")
then output should this
[{
"commentedBy": "test",
"commentId": ObjectId("5b693e7ddd65ec16a46b7f82")
}]
I use this recursive function for remove comments but it's not removing, because we need to pass key of it
async.eachSeries(result[0].comments, function (data, cb) {
function deleteCommentId(comments) {
if (comments.commentId.valueOf() == req.body.commentId) {
delete comments
}
if (comments.subComments) {
deleteCommentId(comments.subComments);
}
return comments;
}
deleteCommentId(data)
return cb();
}, function () {
console.log(JSON.stringify(resultFind))
})
If I have 500 sub comments then we should we able to any of them with its id, any help would be appreciated.
Upvotes: 1
Views: 282
Reputation: 4633
Could you please check if this works well for your requirement?
function retComment(commentArray, id) {
if (commentArray.commentId === id || !commentArray.subComments) {
return [];
} else if (commentArray.subComments && commentArray.subComments.commentId === id) {
return {
"commentedBy": commentArray.commentedBy,
"commentId": commentArray.commentId
}
} else {
retComment(commentArray.subComments, id)
}
}
You need to make the initial call like retComment(commentArray[0], "5b693e7ddd65ec16a46b7f82")
Upvotes: 1