0

I'm using denormalization to manage posts in a blog, so I used to embed the documents as showing below the problem is that I don't know the way to manage documents in subdocument of subdocument

const Post = new Schema({
title:{type:String,required:true,minLength:5},
description:{
    type:String,
    required:true,
    minLenghth:15
},
createdAt:{type:Date,default:Date.now},
author:{type:mongoose.Types.ObjectId ,ref:'users'},
authorName:String,
authorImage:{type:String ,default:"none"},
comments:[
    {
        author:{type:mongoose.Types.ObjectId,ref:'users'},
        authorName:String,
        text:{type:String,minLength:1},
        createdAt:{type:Date,default:Date.now},
        likes:[
            {   
                author:{type:mongoose.Types.ObjectId ,ref:'users'},
                createdAt:{type:Date,default:Date.now}
            }
        ]
    }
],
likes:[
    {
        author:{type:mongoose.Types.ObjectId ,ref:'users'},
        createdAt:{type:Date,default:Date.now}
    }
]
})

and I wanted to add like to comment . Thanks for any help. Moataz

  • Duplicate question ? https://stackoverflow.com/questions/18173482/mongodb-update-deeply-nested-subdocument – mfit Feb 08 '21 at 10:03

1 Answers1

0

based on postId and commentId find the document, after that push your object in likes field

await Post.findOneAndUpdate(
  {
    _id: postId,
    'comments._id': commentsId,
  },
  {$push:{
    "comments.$.likes" : {author : id}
  }}
);
Mohammad Yaser Ahmadi
  • 4,664
  • 3
  • 17
  • 39