Understand MongoDB and Mongoose
MongoDB is a document-oriented NoSQL database.
Instead of storing information in traditional relational tables, MongoDB stores documents inside collections.
A MongoDB document resembles a JSON object, but MongoDB internally stores documents using BSON.
For example, a users collection might contain:
{
"_id": "ObjectId(...) ",
"name": "John Doe",
"email": "john@example.com",
"age": 25,
"isActive": true
}
Mongoose is an Object Data Modeling library that provides a structured way to interact with MongoDB from Node.js.
Mongoose provides:
- Schema definitions.
- Models.
- Validation.
- Middleware hooks.
- Query helpers.
- Population.
- Transactions support through MongoDB sessions.
We will use Mongoose to define and manage our user collection.
MongoDB vs Mongoose
| Feature | MongoDB | Mongoose |
|---|---|---|
| Type | Database | ODM library |
| Storage | BSON documents | No direct storage |
| Schema | Flexible document structure | Application-level schemas |
| Validation | Database validation options | Schema-level validation |
| Execution | Database server | Node.js application |
Key Takeaways
MongoDB stores documents in collections.
Mongoose provides an application-level modeling layer.
Mongoose schemas help enforce consistent document structures.