Express + MongoDB controllers

  1. Make the simplest Schema in models/schemas/product.schema.js for quick start with MongoDb (or go to MongoDb Schema for making a usual projects one).
  2. POST

    Controller POST works with MongoDB

    • Refactor ctrl from local file to work with MongoDB or create controllers/products/addProductCTRL.js (remember about reexports in controllers\products\index.js)

      See the Pen 18 - POST ctrl using for MongoDB by Andrii (@imitator) on CodePen.

      Some errors aren't in list of http-status-codes, so we try to handle them in catch(error){}, other errors we gather in other place by sending them in next(error), in app.js(index.js), this will be explaining in next Catching errors middleware guide

    • Add Catching errors middleware to server.js (or index.js) after all middlewares.
    • Create in routes/products.routes.js the route: router.post('/', ctrl.addProductCTRL);
    • Make some post request (via POSTMAN f.e.)
  3. getAll Refactor controllers\products\getAllProductsCTRL.js for work with MongoDb.

    P.S. Mongoose method Model.find({}) - empty obj {} means to find all documents

  4. getById
    • Make controllers\products\getByIdProductCTRL.js (remember about reexport in controllers\products\index.js)

      See the Pen 22 - getById __ctrl__MondoDb by Andrii (@imitator) on CodePen.

    • Create in routes/products.routes.js the route: router.get('/:id', ctrl.getById);
    • Make a get request in postman for address: http://localhost:5555/api/v1/products/IDfromDataBase
    • P.S. remember about other methods for finding item, like
      Product.findOne({ _id: id });
      Product.findOne({ email });
  5. UPDATE
    • Make controllers\products\updateProductCTRL.js (remember about reexport in controllers\products\index.js)
    • See the Pen 23 - update __ctrl__MongoDb by Andrii (@imitator) on CodePen.

    • Create in routes/products.routes.js the route: router.put('/:id', ctrl.updateProductCTRL);
    • Make a put request in postman for address: http://localhost:5555/api/v1/products/IDfromDataBase
    • P.S. method findIdAndUpdate works like http method PATCH, that means that we may sent only one field with change, not all object.
  6. PATCH
    • In example before (in http method UPDATE) found out that we may use the same route for patching data.
  7. DELETE

    P.S. It is impossible to create "delete" controller name, b/c it is reserved word.

    • Make controllers\products\delProductCTRL.js (remember about reexport in controllers\products\index.js)
    • See the Pen 24 - delete __ctrl__MongoDb by Andrii (@imitator) on CodePen.

    • Create in routes/products.routes.js the route: router.delete('/:id', ctrl.delProductCTRL);
    • Make a delete request in postman for address: http://localhost:5555/api/v1/products/IDfromDataBase
    • P.S. getById, update & delete controllers look for object by id, so if id isn't found in db, mongoDb response error like "Cast to ObjectId failed for..." and according to our Catching errors middleware response code=500, but it isn't really "server error", more "Bad request" with code=400, also frontend developers will understand better error message `Product with id --- ${req.params.id} --- Not Found`. So this kind of error should be caught by commented code in catch(error) {}

  8. Next step of creating a convenient web-server project (but not necessarily, if you do it first time, you should missed this point) is separating transferring information from controllers (means like Model.create(), Model.find()) to separate folder, called services in root of a project. So in this case controllers with services will be look like.

P.S.
There are methods in mongoose, that response us not really necessary info: updateOne, deleteOne, updateMany, deleteMany
return Category.updateOne({ _id: id }, body);

-

return Category.findByIdAndUpdate(id, body);
findByIdAndUpdate - response old object

-

return Category.findOneAndUpdate({ _id: id }, body);
findOneAndUpdate - response old object

-

Setting { new: true } helps response updated obj

return Category.findOneAndUpdate({ _id: id }, body, { new: true });
return Category.findByIdAndUpdate(id, body, { new: true });

Also findByIdAndUpdate updates in object only field, that we would like to update

F.e. obj in db {name: "abc", price: 555}, in request we may write only {price: 123}
To sum up mongoose method findIdAndUpdate works like http method PATCH