Empowering the younger Generation

Empowering the younger Generation


Wednesday, February 21, 2018

Mongoose


What is Mongoose?
 

Mongoose is an object modeling package for Node that
essentially works like an ORM (Object-relational
mapping ) that you would see in other languages.

Mongoose allows us to have access to the MongoDB
commands for CRUD simply and easily.

Mongoose Installation

npm install mongoose --save

Now that we have the package, we just
have to grab it in our project

var mongoose = require('mongoose');

We also have to connect to a MongoDB
database (either local or hosted)

mongoose.connect('mongodb://localhost/
myappdatabase');

Terminology of Mongoose

Mongoose will use the terms Schema
and Model.

What is Schema?
"Mongoose Schema will create a mongodb collection
and defines the shape of the documents within that
collection".
If we want to create a mongodb collection in a structured
manner similar to SQL tables then we can do that using
mongoose Schema.
In the schema creation we will specify the details of fields
like field name, its type, default value if need, index
concept if need, constraint concept if need.


What is Model?
Schemas define a structure we will apply that
Schema part to a model, means "Models are the
constructors compiled from our schema
definitions".

Instances of these models represent documents
which can be saved and retrieved from our
database. All document creation and retrieval
from the database is handled by these models.

 Key Methods and Properties of
Mongoose

Connect() :- Opens the default mongoose
connection.

CreateConnection() :-Will creates a connection
instance and its work is similar to connect()
Schema():-The Mongoose Schema constructor
Model():-The Mongoose Model constructor
Document() :-The Mongoose Document constructor.
Disconnect():- Disconnects all connections

Mongoose Connection

Open(): Opens the connection to MongoDB.
OpenSet():Opens the connection to a replica
set.
close() :Closes the connection, it doesn’t throw
any error even the connection is not opened or
already closed.