title: Repeating code for same operation of different datatypes, Express(nodejs) app with mongoose
body: <p>I am creating an Express rest API that connects to a MongoDB with mongoose. The database has several different datatypes: <code>User</code>, <code>Book</code>, <code>Food</code> and so on. As I am writing endpoints and function for these datatypes. I realized that I am repeating a lot of the same code, for example, for the code below:</p>
  
  <pre><code>// Book.js
  import Book from './models/Book'
  
  function deleteById (req, res, next) {
    Book.findByIdAndRemove(req.params.id, function (err) {
      if (err) {
        let error = new Error('Failed to delete an book in database')
        error.statusCode = 500
        return next(error)
      }
      res.json({
        success: true,
        message: 'Book deleted successfully'
      })
    })
  }
  </code></pre>
  
  <p>I can just change <code>Book</code> to <code>User</code> or <code>Food</code> and the same code can be used. Which results in a lot of repeating code that looks like this:</p>
  
  <pre><code>// Food.js
  import Food from './models/Food'
  
  function deleteById (req, res, next) {
    Food.findByIdAndRemove(req.params.id, function (err) {
      if (err) {
        let error = new Error('Failed to delete an food in database')
        error.statusCode = 500
        return next(error)
      }
      res.json({
        success: true,
        message: 'Food deleted successfully'
      })
    })
  }
  </code></pre>
  
  <p>So I was wondering if there is a way to generate the functions so that I don't need to repeat the code for the <code>deleteById</code> function for each type of data. What would be the best practice? Or is it a bad practice to try to generate the functions and repeating is necessary?</p>
  
  <p>Any help would be really appreciated, thanks in advance.</p>