Search code examples
node.jsmongodbmongooserestful-authentication

How to do user validation on a Mongoose request through Restful


So I want to first find the comment a user wants to delete and then check to see if the usernames match up to validate that the user has permission to do this (I know usernames are not the most secure method this is just for the beta).

This is what I have right now

// Deleting One
router.delete('/delete/:id', (req, res) => {
  const voter = req.body.voter;
  const id = req.params.id;
  var sendContent = {};
  Comments.findById({_id: id}, (error, result) => {
    console.log(`${voter} and ${result.user}`)
    if(voter !== result.user) {
      sendContent.msg = 'You can\'t delete someone else\'s Comment';
      sendContent.code = 500;
      res.send(sendContent);
    } else {
      sendContent.msg = 'Currently in Test Mode but this is where the comment would be deleted';
      sendContent.code = 500;
      res.send(sendContent);
    }
    result.save()
  })
})

is there a result.delete() function or Something? Might be a stupid question but thanks in advance.


Solution

  • No, you'll need to use remove or some of the other delete/find-and-remove functions.

    // Deleting One
    router.delete('/delete/:id', (req, res) => {
      const voter = req.body.voter;
      const id = req.params.id;
      var sendContent = {};
      Comments.findById({_id: id}, (error, result) => {
        console.log(`${voter} and ${result.user}`)
        if(voter !== result.user) {
          sendContent.msg = 'You can\'t delete someone else\'s Comment';
          sendContent.code = 500;
          res.send(sendContent);
        } else {
          sendContent.msg = 'Currently in Test Mode but this is where the comment would be deleted';
          sendContent.code = 500;
          Comments.remove({_id: id}, (err, deleted) =>
            !err && console.log('comment deleted')
            res.send(sendContent)
          );
        }
      })
    })