繁体   English   中英

如何将评论推送到 mongoose model 的评论中,这是一个数组?

[英]How to push a comment into a mongoose model of comment which is an array?

我正在尝试将评论存储在发布请求的评论数组中我的架构如下

const mongoose=require("mongoose")
const bookSchema=mongoose.Schema({
  title:String,
  comments:Array,
  commentcount:Number
})
module.exports=mongoose.model("Book",bookSchema)

以下是我的 app.post

.post(function(req, res){
      let bookid = req.params.id;
      let comments = req.body.comment;
    
      Book.findOneAndUpdate({_id:bookid},
      {
        $push:{comment:comments}//here i wanna push comment
        },
        {
          $inc:{commentcount:1}//here i wanna increment comment count
        })
        .then(
        data=>res.json(data))
    })

除此之外,我想增加添加每条评论的评论数。请帮帮我

你很亲密。 您应该推送到comments字段,并指定comment 只需像这样重构您的代码:

.post(function(req, res){
  let bookid = req.params.id;
  let comment = req.body.comment;
    
  Book.findOneAndUpdate({_id:bookid},
    { $push:{comments: comment} },
    { $inc:{commentcount: 1} 
  }).then(data=>res.json(data))
});

这是工作示例: https://mongoplayground.net/p/J0DeY2IB6WF

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM