![](https://velog.velcdn.com/images/hugh0223/post/1c1b8579-70d2-46be-8c58-3d57bdf801b3/image.png)
🖋️ Node.js 에서 MongoDB 사용
npm i mongoose
-
실행
- mongodb://localhost:27017/[db-name]
import mongoose from "mongoose";
mongoose
.connect('mongodb://localhost:27017/myDB')
.then(() => console.log("connected to mongodb"))
.catch((e) => console.error(e));
import { Schema, model } from "mongoose";
const userSchema = new Schema({
name: String,
age: Number,
email: { type: String, required: true }
});
export default model("User", userSchema);
HTTP 경로를 설정
- Express 사용
- GET, POST, PUT, DELETE
_id 자동 생성
- Mongoose 스키마에서
_id 필드
를 명시적으로 생성 불필요
- MongoDB는 이를 자동으로 처리
- 아래 코드는 post, delete, put 모두
_id
사용
import express from "express";
const app = express();
app.use(express.json());
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
app.post('/users', async (req, res) => {
const user = new User(req.body);
try {
const newUser = await user.save();
res.status(201).json(newUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
app.put('/users/:id', async (req, res) => {
try {
const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(updatedUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
app.delete('/users/:id', async (req, res) => {
try {
const deletedUser = await User.findByIdAndDelete(req.params.id);
res.json({ message: 'User Deleted', deletedUser });
} catch (err) {
res.status(500).json({ message: err.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));