Pushing Nested Object in MongDB

  express, javascript, mongodb, node.js

I want to access nested element from Mongo Schema. What I am trying to do is when user likes a comment of a user id should be pushed in the commentLikes array which is a child of comments if I make commentLikes as a seprate parent each comment have same number of likes for example if user A likes comment 1, his id will also be pushed in comment 2.

My Schema is:

const mongoose = require("mongoose")
const { ObjectId } = mongoose.Schema.Types

const postSchema = new mongoose.Schema({
    subject: {
        type: String,
        required: true
    },
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    photo: {
        type: String,
        default: "https://res.cloudinary.com/bigbrain/image/upload/v1616608676/noQ_hvukdh.png"
    },
    likes: [{
        type: ObjectId,
        ref: "User"
    }],
    comments: [{
        text: String,
        postedBy: { 
            type: ObjectId, 
            ref: "User" 
        },
        commentLikes:[{
            type: ObjectId,
            ref: "User"
        }],
       
    }],
    
    postedBy: {
        type: ObjectId,
        ref: "User"
    },
    postDate:{
        type:String
    }
},{timestamps:true})

mongoose.model("Post", postSchema)

My Backend Code:

  router.put("/likecomment/:id/:comment_id",requireLogin,(req,res)=>{
    const comment = { _id: req.params.comment_id };
    Post.findByIdAndUpdate(req.body.postId,{
        $push:{comments:req.user._id
        }
    },{
        new:true
    }).exec((err,result)=>{
        if(err){
            return res.status(422).json({error:err})
        }
        else{
            console.log(result)
            res.json(result)
        }
    })
})

My Front end code is:

 const likeComment = (commentid) => {
        fetch(`/likecomment/${postid}/${commentid}`, {
            method: "put",
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + localStorage.getItem("jwt")
            },
            body: JSON.stringify({
                postId: commentid
            })
        }).then(res => res.json())
            .then(result => {
                const newData = data.map(item => {
                    if (item._id === result._id) {
                        console.log(result)
                        return result
                    }
                    else {
                        console.log(item)
                        return item
                    }
                })
                setData(newData)
            }).catch(err => {
                console.log(err)
            })

    }

I JUST WANTED TO ACCESS THE commentLikes which is inside comments in backend, I know my logic is correct

 Post.findByIdAndUpdate(req.body.postId,{
        $push:{comments:req.user._id
        }

I also tried accessing commentLikes by comments[commentLikes] but it gives me an error.

Source: Ask Javascript Questions

LEAVE A COMMENT