Express + MongoDB controllers
- 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).
-
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.)
-
Refactor ctrl from local file to work with MongoDB or create
controllers/products/addProductCTRL.js (remember about
reexports in controllers\products\index.js)
-
getAll
Refactor controllers\products\getAllProductsCTRL.js for work
with MongoDb.
P.S. Mongoose method Model.find({}) - empty obj {} means to find all documents
-
See the Pen 21 - getAll ___ctrl__ MongoDB by Andrii (@imitator) on CodePen.
- Make a get request in postman for address http://localhost:5555/api/v1/products or check it in a browser
- This point is more for explanation & useful for frontend developers. In case when a collection doesn't have any items the controller above ☝🏼 response like "[]", so for additional information for frontend developers we add one more checking in code
- This point is needed if we connect products collection with categories collection. Controller with populate() method.
-
-
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 });
-
Make controllers\products\getByIdProductCTRL.js (remember
about reexport in controllers\products\index.js)
-
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.
-
PATCH
- In example before (in http method UPDATE) found out that we may use the same route for patching data.
-
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) {}
-
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.
-
-
-
Setting { new: true } helps response updated obj
Also findByIdAndUpdate updates in object only field, that we would like to update