DEV Community

Cover image for Let's know about Mongoose
Chayti
Chayti

Posted on

Let's know about Mongoose

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:

  1. DBMS VS Object Document Mapper
  2. Stores data VS Manages relationship between data
  3. Supports multiple languages VS Only mondoDB
  4. 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
Enter fullscreen mode Exit fullscreen mode

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:

  1. Array
  2. Boolean
  3. Buffer
  4. Date
  5. Mixed (A generic / flexible data type)
  6. Number
  7. ObjectId
  8. String

We can create a mongoose model by following 3 steps as:

1. Referencing mongoose:

let mongoose = require('mongoose')
Enter fullscreen mode Exit fullscreen mode

2. Defining the schema

let newSchema = new mongoose.Schema({
  variable_name: variable_type
})
Enter fullscreen mode Exit fullscreen mode

3. Exporting a model

module.exports = mongoose.model(collection_name, schema_name)
Enter fullscreen mode Exit fullscreen mode

Basic operations of Mongoose are:

  1. Create record
  2. Fetch record
  3. Update record
  4. Delete record

References:

  1. Introduction to mongoose for mongodb
  2. Mongoose crash course
  3. Reasons to use mongoose
  4. Mongoose tutorial playlist for beginner

Mongoose documentation can be followed for detailed implementation.

Top comments (0)