npm init -y
npm install --save express
To make Node support ES6 for us:
npm install --save @babel/core @babel/node @babel/preset-env
To tell babel how to transpile our ES6 code into common js code that Node JS can execute. (.babelrc)
{
"presets": ["@babel/preset-env"]
}
npx babel-node src/server.js
To parse body of a POST request.
npm install --save body-parser
Whenever your files change, your page will be automatically refreshed.
First install nodemon package:
npm install nodemon --save-dev
Second, run your server using this command:
npx nodemon --exec npx babel-node src/server.js
-
Install Mongo Db on your machine either by running its installation command or downloading from Mongo website.
choco install mongodb
-
Run Mongo shell from "C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe"
-
To create a database
use my-blog
-
In MongoDb each database is composed of a few or many Collections. These collections can contain any number of JSON objects (a.k.a documents).
- Collection name: articles
- documents (array of objects): each JSON object is a document
Our javascript object:
const articlesInfo = { 'learn-react': { upvotes: 0, comments: [], }, 'learn-node': { upvotes: 0, comments: [], }, 'my-thoughts-on-resumes': { upvotes: 0, comments: [], }, };
Insert into our MongoDb collection:
> db.articles.insert([{ name: 'learn-react', upvotes: 0, comments: [], }, { name: 'learn-node', upvotes: 0, comments: [], }, { name: 'my-thoughts-on-resumes', upvotes: 0, comments: [], }])
-
Query data
-
To see all documents
> db.articles.find({})
Or to see it in a readable format use .pretty()
> db.articles.find({}).pretty()
-
To query one document
> db.articles.find({ name: 'learn-react' }).pretty()
Or use .findOne() without .pretty()
> db.articles.findOne({ name: 'learn-react' })
-
Add mongodb library to the project, it allows us to connect and modify our database:
npm install mongodb --save