如何在猫鼬的子文档的子文档中添加文档

时间:2021-02-08 09:56:49

标签: node.js mongodb mongoose

我使用非规范化来管理博客中的帖子,所以我曾经嵌入文档,如下所示 问题是我不知道在子文档的子文档中管理文档的方式

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}
    }
]
})

我想添加点赞评论。 谢谢你的帮助。护城河

1 个答案:

答案 0 :(得分:0)

根据 postId 和 commentId 找到文档,然后将您的对象推送到 likes 字段

await Post.findOneAndUpdate(
  {
    _id: postId,
    'comments._id': commentsId,
  },
  {$push:{
    "comments.$.likes" : {author : id}
  }}
);