简体   繁体   中英

Put and Delete Comment API endpoint - Express MongoDB/Mongoose

I have created an API endpoint that a client can post to and an API endpoint that retrieves the comments.

I am trying to create another API endpoint which allows the client to update an existing comment by specifying the id of the comment they want to change, and a final endpoint to delete. Here is what I have created so far:

var express = require('express');
var router = express.Router();
var Comment = require('../models/comments');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/**
* Adds comments to our database */
router.post('/addComment', function(req, res, next) {
// Extract the request body which contains the comments
    comment = new Comment(req.body);
    comment.save(function (err, savedComment) {
    if (err) throw err;
    res.json({
    "id": savedComment._id
    }); 
});

});

/**
 * Returns all comments from our database
 */
router.get('/getComments', function(req, res, next) {
Comment.find({}, function (err, comments) { if (err)
res.send(err); res.json(comments);
}) });

module.exports = router;

Here are examples of PUT and DELETE functions using ES6 syntax. The update function expects a title and content in the posted body. Yours will look different.

module.exports.commentUpdateOne = (req, res) => {
  const { id } = req.params;

  Comment
    .findById(id)
    .exec((err, comment) => {
      let response = {};

      if (err) {
        response = responseDueToError(err);
        res.status(response.status).json(response.message);
      } else if (!comment) {
        response = responseDueToNotFound();
        res.status(response.status).json(response.message);
      } else {
        comment.title = req.body.title;
        comment.content = req.body.content;

        comment
          .save((saveErr) => {
            if (saveErr) {
              response = responseDueToError(saveErr);
            } else {
              console.log(`Updated commentpost with id ${id}`);
              response.status = HttpStatus.NO_CONTENT;
            }

            res.status(response.status).json(response.message);
          });
      }
    });
};

module.exports.commentDeleteOne = (req, res) => {
  const { id } = req.params;

  Comment
    .findByIdAndRemove(id)
    .exec((err, comment) => {
      let response = {};

      if (err) {
        response = responseDueToError(err);
      } else if (!comment) {
        response = responseDueToNotFound();
      } else {
        console.log('Deleted comment with id', id);
        response.status = HttpStatus.NO_CONTENT;
      }

      res.status(response.status).json(response.message);
    });
};

Usually when you update with PUT in a REST API, you have to provide the entire document's content, even the fields you are not changing. If you leave out a field it will be removed from the document. In this particular example the update function expects both title and content, so you have to provide both. You can write the update logic however you want though.

The router has functions for put and delete. So it will look something like this:

router
  .get('comment/:id', getFunction)
  .put('/comment/:id', putFunction)
  .delete('/comment/:id', deleteFunction);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM