buunguyen / mongoose-deep-populate

Mongoose plugin to enable deep population of nested models ⛺
MIT License
469 stars 44 forks source link

UnhandledPromiseRejectionWarning error on mongoose.remove/router.delete #49

Open charles-passille-smartnets opened 7 years ago

charles-passille-smartnets commented 7 years ago

Not sure if same error as #47 but...

I'm doing deepPopulation of comments in posts, trying to delete comments via ajax delete call. This error occurs on pages that uses the deep populate.

(node:16600) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value "null" at path "_id" for model "Post"
events.js:160
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'commentsIds' of undefined
    at \routes.js:155:24
    at \node_modules\mongoose-deep-populate\lib\plugin.js:70:33
    at \node_modules\mongoose\lib\query.js:2559:9
    at process._tickCallback (internal/process/next_tick.js:103:7)

Routes.js:155 looks like this

router.get('/post/:id', function(req, res) {
  Post.findById(req.params.id).deepPopulate('author commentsIds commentsIds.userId').exec(function(err, post){
      res.render('singlepost', {
        user: req.user,
        title : "post",
        post : post,
        comments : post.commentsIds,   <-- 155
        page : 'singlepost'
      });
    });
});

the delete call looks like this

router.delete('/remove', function(req, res, next){
    Comments.findOneAndRemove({ _id: req.body.comment }, function(err) {
      if (err){
        console.log(err);
      }
      else{
        res.status(200).send({success: true});
      }
    });
});

I know req.body.comment is properly passing through.

The error occurs on the get, like it's trying to reload the page, but it shouldn't as i'm making an ajax post call and event.preventdefault + javascript:void(0) on the tag are properly working.

Any idea? I'm really lost now.

Cheers