Here I chose Express framework for backend, you can find more details about Express in my another post
Express Setup
First use Express generator to generate a simple framework
npm install express-generator -g
Init a project, change directory and install dependencies
express server // use your name here
cd server
npm install
Then we can see files generated
Express Files Explanation
app.js: The entry of this application. In the future, if need to import file externally, remember to add them correspondingly here.
bin: storage of executable files.
node_modules: storage of all dependency packages.
package-lock.json & package.json: store the information about this application and details about dependencies (package name- version pair). Every time when run "npm install", this file will be check first to determine what packages need to be installed. Detect and solve conflicts with the help of this file.
public: storage of css, image, js files.
routes: router files. This is the part I will particularly focus on.
views: storage of template files.
Mongoose Setup
The application will connect to a MongDB database, I chose to use Mongoose to operate database.
cd server // change directory to your application
npm install --save mongoose
Here are few other options you can use here, mongoose is needed for both dev and production environments, so I chose save here.
After all of these, files structure looks like this
Connect to MongoDB database
To begin with, let's define schema, I created a separate folder to store all my models
Config and connection to DB, again I created a separate folder to store config info
Then we can define some operations, for example here I defined two GET operations, get whole user collection and find user with particular name
So far, all of these three components are still invisiable for application. Remember I said app.js is the entry, so we need to add these components into that file, then when application starts, it will have them.
This is how file structure looks like now
Test Tools
Now let's do some tests, here are some useful tools to help us do test easier.
Rubo3T (formally RuboMongoDB), this tool can help you directly visualize what do you have in your database and documents in collections.
Postman: can test the response of the request you send to backend, in this way you don't need to wait until you have a workable frontend.
Lots of installation instruction can be found easily online, I won't talk about that part. Just one tip here, if you see "exception in initAndListen: NonExistentPath: Data directory /data/db not found.", create /somepath/data/db directory and run ./mongod --dbpath /somepath/data/db to set db path.
Test
Let's mock some documents in MongoDB
Start Express
npm start
I got this warning
Let's take a closer look, seems like our parser is out-of-date. Fix as follow.
Get all users result
Now we have confidence backend Express is working. Next post, we are going to move to front end, how to send request.