Saturday, August 10, 2019

Mongoose

Image result for mongoose logo



Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

MongoDB is a schema-less NoSQL document database. It means you can store JSON documents in it, and the structure of these documents can vary as it is not enforced like SQL databases. This is one of the advantages of using NoSQL as it speeds up application development and reduces the complexity of deployments.


Collections


‘Collections’ in Mongo are equivalent to tables in relational databases. They can hold multiple JSON documents.

Documents.
‘Documents’ are equivalent to records or rows of data in SQL. While a SQL row can reference data in other tables, Mongo documents usually combine that in a document.
Fields
‘Fields’ or attributes are similar to columns in a SQL table.

Schema

While Mongo is schema-less, SQL defines a schema via the table definition. A Mongoose ‘schema’ is a document data structure (or shape of the document) that is enforced via the application layer.

Models

‘Models’ are higher-order constructors that take a schema and create an instance of a document equivalent to records in a relational database.
Getting Started

Mongo Installation

Before we get started, let’s setup Mongo. You can choose from one of the following options :
Download MongoDB version for your Operating System from the MongoDB Website and follow their installation instructions

Create a free sandbox database subscription on mLab
Install Mongo using Docker if you prefer to use docker


How to install  Mongoose by terminal?

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');

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 the 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.

No comments:

Post a Comment

Express

In this tutorial, we will also have a look at the express framework. This framework is built in such a way that it acts as a minimal an...