mongo-db.js
const mongoose = require("mongoose");
// 스키마와 모델 정의
const planetSchema = new mongoose.Schema({});
// const testPlanetSchema = new mongoose.Schema({});
const Planet = mongoose.model("Planet", planetSchema);
const TestPlanet = mongoose.model("TestPlanet", planetSchema);
exports.mongoDB = async () => {
try {
await mongoose.connect("mongodb+srv://hr:"패스워드입력"@cluster0.bjwmlof.mongodb.net/sample_guides", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("Connected to MongoDB");
} catch (error) {
console.error("MongoDB connection failed:", error);
}
};
exports.Planet = Planet;
exports.TestPlanet = TestPlanet;
server.js
const express = require("express");
const app = express();
const { mongoDB, Planet, TestPlanet } = require("./config/mongo-db");
app.listen(8088, async function () {
try {
await mongoDB();
console.log("Connected to MongoDB");
const planets = await Planet.find();
const testPlanets = await TestPlanet.find();
console.log("Planets:", planets);
console.log("Test Planets:", testPlanets);
} catch (error) {
console.error("Error:", error);
}
});
Atlas에서 제공하는 테스트DB를 넣어서 테스트 진행함.
여러개의 테스트 데이터가 제공되는데 그 중에서 sample_guides 데이터베이스의 planets 컬렉션을 조회해보기로 함
** 관계형과 document형의 구조 비교
커넥션 주소를
mongoose.connect("mongodb+srv://hr:"비밀번호"@cluster0.bjwmlof.mongodb.net/sample_guides"
와 같이 "sample_guides"라는 데이터베이스로 지정해주었음
스키마를 정의할때 모델의 이름을 Planet이라고 지정한걸 볼 수 있는데 실제 컬렉션의 이름은 planets임
이름이 다른 이유는 mongoose의 동작방식에 있음.
몽고디비는 기본적으로 컬렉션 이름을 소문자로 만들고 복수형으로 변환하여 사용함.
하지만 관례적으로 몽구스에서는 모델의 이름을 단수형으로, 컬렉션의 이름을 복수형으로 사용하는 것을 권장함.
이렇게 하면 코드를 읽을 때 몽고디비 컬렉션과 몽구스 모델 간의 관계를 더 쉽게 이해할 수 있다고 하는데 아직은 잘 모르겠음...
모델 이름을 실제 컬렉션 이름과 동일하게 해도 무관함
ex)
const testplanets = mongoose.model("testplanets", planetSchema);
-----
const testplanetsList = await testplanets.find();
'Mongo DB' 카테고리의 다른 글
React/Node/MongoDB CRUD 예시 (0) | 2023.09.02 |
---|---|
Node.js, MongoDB 연동 (0) | 2023.08.30 |