Home > Software design >  Inesrt data into Nested Array (comment action) MongoDB
Inesrt data into Nested Array (comment action) MongoDB

Time:11-06

I'm building a simple social platform; I'm currently building out the schema for commenting on a post, but users should be able to comment on other comments as well. So what I'm trying to do is, once a user comments on the post, a condition is being checked whether the postId params matches the post._id in the database, therefore this is a higher order comment action. Now if I were to comment on somebody else's comment, I would be checking whether the post._id matches the post as well as checking whether the comment._id matches as well, but I'm having issues by inserting it into the nested array.

Schema (POST)

onst mongoose = require('mongoose');
const Schema = mongoose.Schema;

const postSchema = new Schema({
    uid: { 
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: "users",
    },
    uname: {type: String, required: true},
    upic: {type: String, required: true},
    message: { type: String,},
    media: {type: String,},
    likes:[],
    comments:[],
    commentCount: {type: Number, default: 0},
    likeCount: {type: Number, default: 0},
    repostCount: {type: Number, default: 0},
    postedOn: { type: Date},
});

postSchema.pre('save', function(next){
    this.postedOn = Date.now();
    next();
});

var PostModel = mongoose.model('posts', postSchema);

module.exports = PostModel;

Controller (Comment)

{/* Higher order comment */}
module.exports.commentPost = async (req, res) => {
    try{
        await PostModel.findByIdAndUpdate(req.params.postId, 
        {
            $push: {
                comments: [{
                    _id: uuid.v1(),
                    postId: req.params.postId,
                    uid: req.user._id,
                    message: req.body.message,
                    postedOn: Date.now(),
                    uname: req.user.name,
                    upic: req.user.pic,
                    likes: [],
                    comments: [],
                    likeCount: 0,
                    commentCount: 0,
                }]
            },
            $inc: { commentCount: 1}
        }).exec((err,result)=>{
            if(err){
                return res.status(422).json({error:err})
            }else{
                res.json(result)
            }
        });

    } catch(err){
        throw new ErrorResponse(err, 404);
    }
}

{/* Lower order comment */}
module.exports.commentCommentPost = async (req, res) => {
    try{
        await PostModel.findByIdAndUpdate({"_id": req.params.postId, "comments._id": req.body.commentId}, 
        {
            $push: {
                comments: [{
                    comments: [{
                        _id: uuid.v1(),
                        postId: req.params.postId,
                        uid: req.user._id,
                        message: req.body.message,
                        postedOn: Date.now(),
                        uname: req.user.name,
                        upic: req.user.pic,
                        likes: [],
                        comments: [],
                        likeCount: 0,
                        commentCount: 0,
                    }]
                }]
            },
            $inc: { commentCount: 1}
        }).exec((err,result)=>{
            if(err){
                return res.status(422).json({error:err})
            }else{
                res.json(result)
            }
        });

    } catch(err){
        throw new ErrorResponse(err, 404);
    }
}

I must be doing something wrong by updating the nested array within a nested array, any help would be appreciated.

CodePudding user response:

I was able to fix the issue, here is the solution on what I've done, which works perfectly fine now.

module.exports.commentCommentPost = async (req, res) => {
    try{
        await PostModel.update({_id: req.params.postId, 'comments._id': req.body.commentId}, 
        {
            $push: {
                'comments.$.comments': {
                        _id: uuid.v1(),
                        postId: req.params.postId,
                        uid: req.user._id,
                        message: req.body.message,
                        postedOn: Date.now(),
                        uname: req.user.name,
                        upic: req.user.pic,
                        likes: [],
                        comments: [],
                        likeCount: 0,
                        commentCount: 0,
                }
            }
        }).exec((err,result)=>{
            if(err){
                return res.status(422).json({error:err})
            }else{
                res.status(200).json(result)
            }
        });

    } catch(err){
        throw new ErrorResponse(err, 404);
    }
}
  • Related