Mongoose mongodb, remove an element on an array Mongoose mongodb, remove an element on an array mongoose mongoose

Mongoose mongodb, remove an element on an array


You need to remove the comment id from the array manually. The better way to do this is adding a remove middleware to your comment schema:

commentSchema.pre('remove', function (next) {  User.update(    { comments: this },     { $pull: { comments: this._id } },     { multi: true }  ).exec(next)})

But remove middlewares are only executed by calling doc.remove, and not Model.findByIdAndRemove. So you need to change a little your code (I'm using promises here for a better readability, but you can do this with callbacks):

app.delete('/index/:id/comments/:comment_id', function (req, res) {  Comment.findById(req.params.comment_id)    .then(function (comment) {      return comment.remove() // doc.remove will trigger the remove middleware    })    .then(function () {      console.log('Comment successfully deleted!')      return res.redirect('back')    })    .catch(function (err) {      console.log(err)      res.redirect('/index')    })})