Mongoose:
MongoDB is a nosql, document oriented database program. It stores JSON-like documents with optional schema. But, Mongoose is an Object Data Modelling (ODM) for mongodb and nodejs. It manages relationships between data. It defines a schema for collections.
MongoDB VS Mongoose:
- DBMS VS Object Document Mapper
- Stores data VS Manages relationship between data
- Supports multiple languages VS Only mondoDB
- Aim - Storing collection in DB VS Defining schema for collections.
Mongoose defines schema and also validates it. It helps to structure the document for better presentation. It enables users to add/ edit properties easily.
To use this, at first we have to install mongoose, like,
npm install mongoose --save
Once we define a schema, we can create a Model based on a specific schema in Mongoose. After creation of the model, a Mongoose Model is then mapped to a MongoDB Document and it is done via the Model's schema definition.
The permitted schema types are:
- Array
- Boolean
- Buffer
- Date
- Mixed (A generic / flexible data type)
- Number
- ObjectId
- String
We can create a mongoose model by following 3 steps as:
1. Referencing mongoose:
let mongoose = require('mongoose')
2. Defining the schema
let newSchema = new mongoose.Schema({
variable_name: variable_type
})
3. Exporting a model
module.exports = mongoose.model(collection_name, schema_name)
Basic operations of Mongoose are:
- Create record
- Fetch record
- Update record
- Delete record
References:
- Introduction to mongoose for mongodb
- Mongoose crash course
- Reasons to use mongoose
- Mongoose tutorial playlist for beginner
Mongoose documentation can be followed for detailed implementation.
Top comments (0)