Trung BìnhDatabase iconDatabase

Mongoose là gì? Schema trong Mongoose hoạt động như thế nào?

Mongoose thêm schema, validation, và middleware (hooks) lên MongoDB — dùng lean() cho read-only queries (2-3x nhanh hơn), populate() cho references nhưng cẩn thận N+1.

  • Mongoose là ODM (Object Document Mapper) cho MongoDB trong Node.js, giúp thêm structure vào schemaless MongoDB.
  • Middleware (hooks) có 4 loại: document middleware (pre/post save, validate, remove — this là document), query middleware (pre/post find, findOne, update — this là query), aggregate middleware (pre/post aggregate), model middleware.
  • Virtuals: computed properties không lưu trong DB — ví dụ fullName computed từ firstName + lastName, hay URL computed từ slug; có thể include trong JSON với toJSON({ virtuals: true }).
  • Populate: thay thế ObjectId references bằng actual documents — populate('author') fetch User document; nhưng cẩn thận N+1, dùng populate với select để limit fields. lean(): trả về plain JavaScript objects thay vì Mongoose documents — nhanh hơn 2-3x vì bỏ overhead của Mongoose document methods; dùng khi chỉ cần read-only data.

Pitfall: Mongoose buffering commands trước khi kết nối — cần handle connection errors properly.

Xem toàn bộ Database cùng filter theo level & chủ đề con.

Mở danh sách Database