Ashwin Joshy
Ashwin Joshy

Reputation: 49

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

I am trying to store comment in an array of comments on post request My schema is as follows

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

following is my 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))
    })

in addition to that i wanna increase the comment count on adding each comment.Please help me with it

Upvotes: 1

Views: 80

Answers (1)

NeNaD
NeNaD

Reputation: 20304

You are close. You should push to comments field, and you specified comment. Just refactor your code like this:

.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))
});

Here is the working example: https://mongoplayground.net/p/J0DeY2IB6WF

Upvotes: 2

Related Questions