몽고 DB 기본 연결하기
const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
mongoose
.connect(
"mongodb+srv://username:<password>@cluster0.3rt3shc.mongodb.net/?retryWrites=true&w=majority"
)
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));
app.get("/", (req, res) => {
res.send("Hello World! 안녕하세요!");
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
비밀번호에 특수문자가 들어가있으면 encodeURIComponent을 이용해서 인코딩해서 사용하자
const username = encodeURIComponent("<username>")
const password = encodeURIComponent("<password>")
const express = require("express");
const app = express();
const port = 3000;
// 특수문자가 있다면 encodeURIComponent 함수로 인코딩 후..
const username = encodeURIComponent("<username>")
const password = encodeURIComponent("<password>")
const mongoose = require("mongoose");
// 템플릿 리터럴로 값을 문자열에 넣는다.
mongoose
.connect(
`mongodb+srv://${username}:${password}@cluster0.3rt3shc.mongodb.net/?retryWrites=true&w=majority`
)
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));
app.get("/", (req, res) => {
res.send("Hello World! 안녕하세요!");
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
dotenv
https://www.npmjs.com/package/dotenv
dotenv 파일을 만들어서 비밀번호나 key 같은 것을 별도로 관리하자
설치방법
npm i dotenv
사용방법
require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it is working
'node.js' 카테고리의 다른 글
node.js next 함수를 이용한 Express 미들웨어 실행 (0) | 2024.01.04 |
---|---|
express, react 이미지 업로드 서버 (0) | 2023.09.17 |
몽고db 기본 연결