
db.jsํ์ผ
import mongoose from "mongoose";
import dotenv from "dotenv";
dotenv.config();
mongoose.connect(process.env.Mongo_URL, {
useNewUrlParser: true,
useFindAndModify: false,
//configuration์ ์ค์
});
// mongoose.connect()
// string์ผ๋ก ๋ ๋ฐ์ดํฐ๋ฒ ์ด์ค๋ฅผ ์์ฒญํ์ฌ ์ด๋์ ๋ฐ์ดํฐ๋ฒ ์ด์ค๊ฐ ์ ์ฅ๋์ด์๋์ง ์๋ ค์ค๋ค.
// Mongo_URL = "mongodb://127.0.0.1:27017/serverPractice"
const db = mongoose.connection;
// mongoose.connection.once๋ก ๋ฐ๋ก ์ฐ๊ฒฐํด๋ ๋์ง๋ง ์ถ์ฝ์ ์ํด const์ ์ ์ฅํด๋์.
const handleOpen = () => console.log("โ
Connected to DB");
const handleError = (error) => console.log(`Error on DB Connection:${error}`);
db.once("open", handleOpen);
db.on("error", handleError);
// ์ฐ๊ฒฐ, ์๋ฌ, ์ ์ ๋๊น์ด ์ผ์ด๋๋ฉด ์ฝ๋ฐฑํจ์๋ฅผ ์คํํ๋ค.
// ์ฐ๊ฒฐ์ด ๋๊ธธ ์ ์๋์ผ๋ก ์ฌ์ ์์ ์คํํ๋ค.
init.jsํ์ผ
import "/db"
When you need to import something that doesn't export anything, but does something else, this is a side effect only module. You import it only to initialize it.
npm start๋ก init.js๋ฅผ ์คํํ๋ฉด database server์ ์ฐ๊ฒฐ๋๊ณ , Connected to DB๊ฐ ๋ก๊ทธ์ ๋จ๋ ๊ฒ์ ๋ณด๋ฉด 'db.js'๋ exportํ๋ ๊ฒ์ ์์ง๋ง, ํ์ผ์ด ๋ถ๋ฌ์์ ธ์ ์คํ๋๋(initialize) ๊ฒ์ 'Import a module for its side effects only'๋ผ๊ณ ํ๋ ๋ฏ ํฉ๋๋ค.
๋ฐ์ํ
'๐ Back > ๐ MongoDB' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| MongoDB Atlas ๋ฑ๋ก&์ฌ์ฉ (๋ฌด๋ฃ mongoDB Cloud ์๋น์ค) (0) | 2021.05.18 |
|---|---|
| ์คํค๋ง ๋ง๋ค๊ธฐ: ์คํค๋ง, ๋ชจ๋ธ, ์ปฌ๋ ์ (0) | 2021.02.05 |
| MongoDB ๋? ๋ํ์ ์ธ NOSQL ๋ฐ์ดํฐ๋ฒ ์ด์ค (0) | 2021.01.19 |