0

NodeJS Bài 5 - Cài đặt Mongoose

1. Cài đặt mongoose

npm install mongoose

2. Cấu trúc thư mục cơ bản

project/
├── app.js
├── models/
│   └── book.model.js
└── package.json

3. Kết nối MongoDB trong app.js

const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = 3000;

app.use(express.json());

// ⚡ Kết nối MongoDB
mongoose.connect('mongodb://localhost:27017/bookstore', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', (err) => console.error('❌ MongoDB connection error:', err));
db.once('open', () => console.log('✅ Connected to MongoDB'));

// 🔽 Route thử nghiệm
const Book = require('./models/book.model');

app.get('/api/books', async (req, res) => {
  const books = await Book.find();
  res.json(books);
});

app.listen(PORT, () => {
  console.log(`🚀 Server running at http://localhost:${PORT}`);
});

4. Tạo Schema Mongoose

models/book.model.js

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  price: Number,
  stock: Number,
}, { timestamps: true });

module.exports = mongoose.model('Book', bookSchema);

Nhiên.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí