Express + Mongoose. Sample solution
Clone this repo.
git clone https://github.com/ZufengW/INFO30005-w5-pre.git
cd
into the repo.
Then install dependencies.
npm install
Note that db.js
uses the environment variable DB
.
You need to provide a value for this if you want the database to work.
Here is one way to run the app and provide an environment variable.
(Replace YOUR_MONGODB_URI
with your actual database connection string)
DB=YOUR_MONGODB_URI nodemon app
Then you can visit the website in your browser: http://localhost:3000/users/ (This is like sending GET requests)
Use a REST client such as Postman or Advanced REST Client to send http requests to your server.
INFO30005-w5-pre
├─┬ controllers
│ └── controller.js Defines callback functions for routes
├─┬ models Mongoose stuff
│ ├── db.js Set up connection to database
│ └── users.js User model
├── node_modules Contains dependencies. Don't commit this file.
├─┬ routes
│ └── users.js Defines CRUD routes for users
├── .gitignore Specify things you don't want version-controlled
├── app.js Runs the app
├── package.json Contains info about the project
├── package-lock.json Contains more info about dependencies (don't edit this directly)
└── README.md Contains info about the project for humans to read
To avoid committing secrets such as API keys into your repo. You wouldn't want people to find out this info if you make your repo public.
It is an arrow function, which is a alternative to regular function expressions.
It can be more compact than writing function
.
const
is for declaring constants. Constants are block-scoped and can't be reassigned or redeclared. Useconst
wherever possible because it's the most restrictive.let
is likeconst
, except they can be reassigned.- Avoid using
var
because the variable can be reassigned, redeclared and it is function scope.
One possibility is http://mongodb.com/atlas, where you can get a free-tier cluster in the cloud.
Summary of steps:
- Make an account
- Build a new cluster
- (e.g. AWS, Singapore, M0 tier)
- Add a user to it with read and write access
- Whitelist your IP addresses (or allow global access, which is easier)
- Overview > Connect > Connect your application.
- Copy the connection string.
- Make sure to substitute in the user's password. The password needs to be URL encoded
It's also possible to get MongoDB running locally on your machine.
||
is logical OR.
If the left side (process.env.PORT
) evaluates to something falsy (such as undefined
), then the entire expression evaluates to the right side (3000
).
Use this if you want to have a value with fallback to another value if the first value was undefined
.