ExpressJS & Mongoose REST API structure: best practices?
Well, you can separate out your routes, db models and templates in different files.Have a directory structure something like this,
| your_app| -- routes| -- models| -- templates| -- static | -- css | -- js | -- images| -- config.js| -- app.js| -- url.js
- For each Mongoose model have a separate file placed in your
./models
- In templates directory place your jade files. (Assuming you are using jade as your template engine). Though it seems like you are only serving JSON, not HTML. Consider using Jade if you want to render HTML. (Here are few other template engines you can consider going with)
./static
directory for static JS, CSS and XML files etc.- Things like db connections or 3rd party API keys and stuff can be put in config.js
- In url.js have a procedure which take express
app
object as argument and extend uponapp.get
andapp.post
there in single place.
P.S. This is the approach I go with for a basic web app in express. I am in no way saying this the best way to follow, but it helps me maintain my code.
As codemonger5 said there is no right way of organising directory structure.
However, you can use this boilerplate application for creating REST APIs using Express and mongoose using ES6. We use the same directory structure in our production API services.
git clone https://github.com/KunalKapadia/express-mongoose-es6-rest-apicd express-mongoose-es6-rest-apinpm installnpm start