A
A
Andrew2018-11-26 01:11:21
MongoDB
Andrew, 2018-11-26 01:11:21

How to add new object to MongoDB array?

There is such a scheme:

var PostSchema = new Schema({
  title: String,
  description: String,
  content: String,
  image: String,
  category: String,
  url: String,
  views: {
    type: Number,
    default: 0
  },
  comments: [
    {
      username: String,
      email: String,
      comment: String
    }
  ]
});

I can't figure out how to correctly add another comment to the comments array.
Tried like this, but it doesn't seem to be even close to what I need.
router.put('/blog/:url/add-comment', (req, res) => {
    let db = req.db
    Post.updateOne({ 'url': req.params.url }, {$push: {comments: {
      'username': req.body.comments.username,
      'email': req.body.comments.email,
      'comment': req.body.comments.comment
    }}})

By the way, if for example I have a separate method for updating the counter of views and there is a form for adding comments, both use the Put method, then each needs a separate route (/post/:url/update-conter, /post/:url/new-comment ) , or is it possible to pass different methods on one route?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question