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.
-
How much deep can this object be? Is there any limit to it?Tushar Shukla– Tushar Shukla2018年08月07日 09:27:29 +00:00Commented Aug 7, 2018 at 9:27
-
You need to create a recursive function to achieve this. First in subcomment match the Object If if it is matched then delete the whole object. Otherwise search the child apply the same logicDeepak Kumar– Deepak Kumar2018年08月07日 09:29:03 +00:00Commented Aug 7, 2018 at 9:29
-
@TusharShukla no there is no limit, I have an id of it.Raj Jaril– Raj Jaril2018年08月07日 09:29:17 +00:00Commented Aug 7, 2018 at 9:29
-
@DeepakKumar I have created recursive function as well but problem is that, if they pass the very first parent id then it should remove from the array, I have already managed sub comment but not able to do with very first parent :(Raj Jaril– Raj Jaril2018年08月07日 09:32:23 +00:00Commented Aug 7, 2018 at 9:32
-
ObjectId("5b693e7ddd65ec16a46b7f82") is a function call with parameter, right?Tushar Shukla– Tushar Shukla2018年08月07日 09:32:47 +00:00Commented Aug 7, 2018 at 9:32
1 Answer 1
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")