NodeJS – 5. Connect MongoDB

Author: - Posted: 05/05/21 - Update: 05/05/21

I. Cấu hình MongoDB

1. Dùng trên Localhost: MongoDB Compass

- Download: https://www.mongodb.com/try
- Vào Onpremises -> MingoDB Community Server -> Download -> Install bình thường
- Để link truy cập Localhost tại file .env

MONGO_LOCALHOST=mongodb://localhost:27017/medihome

2. Tạo Project trên MongoDB

1.1. Tạo Cluster
- Đăng nhập -> Tạo Project (2 bước: Tên Project và add Member)
- Build Cluster
1.2. Connect Cluster
- Cài Network Access: IP được phép truy cập trước (nên chọn 0.0.0.0/0 -> có thể truy cập mọi nơi để tránh phát sinh lỗi)
- Cài tài khoản có quyền truy cập
1.3. Cấu hình
- Để link truy cập MongoDBtại file .env

MONGODB_URI=mongodb+srv://root:[email protected]/test?retryWrites=true

II. Kết nối MongoDB

1. Cấu hình file ./.env

2. Dùng mongodb

1.1. Cài đặt thư viện:
https://www.npmjs.com/package/mongodb

npm i mongodb

1.2. Tạo file: src/config/database/mongoDB.js

1.3. Tại file: src/server.js

1.4. Sử dụng

3. Dùng mongoose

2.1. Cài đặt thư viện:
-- Github: https://github.com/Automattic/mongoose

npm install mongoose

3.2. Tạo file: src/config/database/mongo.js

3.3. Tại file: src/server.js

3.4. Sử dụng