Hướng dẫn tạo project NodeJS và connect mongodb

Hướng dẫn tạo project NodeJS và connect mongodb

Prerequisites

  • Install NodeJS: Linux or Windows
  • Install Yarn: npm install -g yarn

Init project

touch index.js
yarn init -y

Install packages

yarn add express mongoose body-parser cors nodemon dotenv
  • express: nodejs frameword help to create routing for app
  • mongoose: help to create model for database
  • body-parser: express middleware
  • dotenv: Load environment variables from .env file

Connect database

  1. Goto Google and search "mongo atlas"
  2. Login with google
  3. Create a cluster
  4. Choose AWS and server Singapore => click Create Cluster
  5. Goto Database Access => Add New Database User => Filling all info => Add User
  6. Goto Network Access => Add IP Address
  7. Back to Cluster => click CONNECT => Choose "Connect your application"
  8. Add connect db to index.js

Initial Code for index.js

import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import mongoose from 'mongoose';
import postsRouter from './src/routers/posts.js';
import crawlerRouter from './src/routers/crawler.js';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
const DATABASE_URL = process.env.DATABASE_URL;
app.use(bodyParser.json());
// Limit the data which the client will submit on server
app.use(bodyParser.urlencoded({ extended: truelimit: '30mb' }));
app.use(cors());
app.use('/posts'postsRouter);
app.use('/crawl-data'crawlerRouter);
mongoose.connect(DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: trueuseFindAndModify: false
}).then(() => {
console.log('Connected to database!');
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
}).catch((error=> {
console.log('Error'error);
})

Create .env file at root folder

PORT = 5000
DATABASE_URL = 'url'

Run project

  1. Add code below to package.json
    "scripts": { "start""nodemon index.js"
    },
  2. Run command line: yarn start

Create project structure

mkdir src
cd src
mkdir routers
mkdir controllers
mkdir models

Đăng nhận xét

Mới hơn Cũ hơn