Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const getAllCommentByBlogId = async ({id}, req) => {
- try {
- const {isAuth} = req //get the authenticated user status
- if (isAuth) { //if the user is authenticated then it will execute
- const getAllComment = await Comment.find (
- {
- "blog": id,
- // isDelete: false
- }
- ).populate({
- path: "user",
- select: `
- personalInfo.firstName
- personalInfo.lastName
- personalInfo.profileImage
- personalInfo.email
- -_id
- `
- }).select (`
- commentId
- content
- inherit
- isDelete
- -_id
- `)
- if (getAllComment.length != 0) { //if comment found then it will happen
- const allComment = getAllComment
- //but it filtered same things but not working
- const parent = allComment.filter (data => !data.inherit) //get all root parent comment
- //parent will give
- /*parent: [
- {
- commentId: 'CMNT87566',
- inherit: '',
- user: [Object],
- content: 'Hello I am John',
- isDelete: false
- }
- ]*/
- //when i gave this it works
- const parentOne = [
- {
- commentId: 'CMNT87566',
- content: 'Hello I am X',
- inherit: '',
- isDelete: false,
- user : {
- personalInfo: {
- firstName: "Mr",
- lastName:"John"
- }
- }
- }
- ]
- console.log({parentOne, parent})
- function recursive (parent) {
- parent.map (singleParent => {
- singleParent.child = []
- allComment.map (singleChild => {
- if (singleChild.inherit == singleParent.commentId) {
- singleParent.child = [...singleParent.child, singleChild]
- }
- })
- if (singleParent.child.length) {
- recursive(singleParent.child)
- }else {
- singleParent.child = []
- }
- })
- }
- recursive(parent)
- }else {
- return {
- message: "No Comment Found"
- }
- }
- }else {
- return {
- message: "Unauthorized user"
- }
- }
- }catch (err) {
- return {
- message: err.message
- }
- console.log(err)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement