Nodejs and MongoDB – Introduction to Mongoose (Coding) | Learn Nodejs MongoDB

Learn Nodejs MongoDB with Simple Example

Mongoose is a library of nodejs that provides a solution based on schemes to model the data from your application. It has conversion system types, validation , creating queries and hooks for business logic.

Mongoose provides a mapping of MongoDB objects similar to ORM (Object Relational Mapping ) , or ODM ( Object Data Mapping) in the case of Mongoose . This means that the Mongoose translates data from the database to JavaScript objects so they can be used by your application.

Note : This article will assume that you have installed nodejs and MongoDB . You need to be with MongoDB running on your computer to make the following
examples.




Installing Mongoose package

Using the [ NPM ] [ ] via the command line is very simple to install the nodejs packages. To install the Mongoose , run the following command line that the NPM will take care to install the latest stable version of the required package:

Install Mongoose

Connecting to MongoDB

In this article we will connect the Mongoose with the test database MongoDB defines when you boot the console and we will ensure that any connection error is printed on the console.

var Mongoose = require(‘Mongoose’);
var db = Mongoose.connection;

db.on(‘error’, console.error);
db.once(‘open’, function() {
console.log(‘ Connected to MongoDB.’)
// Let’s add our Schemes, Models and queries here

});

Mongoose.connect(‘mongodb://localhost/test’);
When running our sample application can be seen on the island of MongoDB that were opened 5 simultaneous connections. This is because the Mongoose uses a set of five simultaneous connections by default that are shared throughout your application. To improve the performance of our applications we will leave them open , however you can change the default behavior by adding optional parameters to Mongoose.connect () – the poolSize parameter sets the amount of simultaneous connections. Below is the output of my MongoDB displaying that were opened 5 simultaneous connections :
Sat Aug 31 11:12:21.827 [initandlisten] connection accepted from 127.0.0.1:64413 #2 (1 connection now open)
Sat Aug 31 11:12:21.830 [initandlisten] connection accepted from 127.0.0.1:64414 #3 (2 connections now open)
Sat Aug 31 11:12:21.831 [initandlisten] connection accepted from 127.0.0.1:64415 #4 (3 connections now open)
Sat Aug 31 11:12:21.831 [initandlisten] connection accepted from 127.0.0.1:64416 #5 (4 connections now open)
Sat Aug 31 11:12:21.832 [initandlisten] connection accepted from 127.0.0.1:64417 #6 (5 connections now open)

Schemes and Templates

To begin we need a scheme and a model that can work with the data that will be persisted in our MongoDB database. Schemas define the structure of documents within a collection and models are used to create instances of data that will be stored in documents. We will make a movie database to track the movies have extra scenes after the final credits (also called ‘ credit cookies ) . The code below shows our movieSchema scheme and our Movie model created .

var movieSchema = new Mongoose.Schema({
title: { type: String },
rating: String,
releaseYear: Number,
hasCreditCookie: Boolean
});

var Movie = Mongoose.model(‘Movie’, movieSchema);

The last line of this code compiles the Movie template using the movieSchema scheme like structure. The Mongoose also creates a collection in MongoDB called Movies for these documents .

You may notice that the Movie model is upper case , this is because when a model is compiled is returned a constructor function that will be used to create instances of the model . The bodies created by the model builder are documents that will be persisted by MongoDB to use the save function .
Create, Retrieve , Update, and Delete (CRUD )

Create a new document Movie it is easy now that we have defined the model , just instancializar Movie template and save this instance the base. Upgrading is also easy , make your changes and then call the save function of your document.

var thor = new Movie({
title: ‘Thor’,
rating: ‘PG-13’,
releaseYear: ‘2011’, // Note o uso de String ao inves de Number
hasCreditCookie: true
});

thor.save(function(err, thor) {
if (err) return console.error(err);
console.dir(thor);
});

Note that we use a string instead of a number in releaseYear field and the Mongoose will be in charge of converting the data to the type specified in the scheme .

When we add these two codes data to our application and we perform the function will provide save a newly created document , seen by what was printed on the console of our application.

{ __v: 0,
title: ‘Thor’,
rating: ‘PG-13’,
releaseYear: 2011,
hasCreditCookie: true,
_id: 5222012cb65eddf003000001 }

Collections in MongoDB have flexible schemes, this means that collections do not impose the structure of the documents. In practice this means that documents from the same collection need not have the same set of fields or structure, and common fields in documents of a collection can carry different types of data. As seen in our example, using the Mongoose to map our base, it standardizes the documents of the same scheme to ensure that instances of the model who compiled that scheme always have the same data type in the attributes specified by the scheme.

MongoDB also has a data structure called index that allows you to quickly locate documents based on the values stored in specific fields. Fundamentally, indexes in MongoDB is similar to rates in other database systems. In our example the index created model is _id.
Recovering a base document

Different ways can be used to retrieve an existing document in the database. You can search for documents based on any scheme property and you can get any number of documents. Use findOne to limit the results to a single document.

// Seeking a single movie by name
Movie.findOne({ title: ‘Thor’ }, function(err, thor) {
if (err) return console.error(err);
console.dir(thor);
});

// Seeking all movies
Movie.find(function(err, movies) {
if (err) return console.error(err);
console.dir(movies);
});
// Searching all the movies that have ‘ credit cookie
Movie.find({ hasCreditCookie: true }, function(err, movies) {
if (err) return console.error(err);
console.dir(movies);
});

Mongoose also lets you create static helper functions to get your data. For this you must assign a static function to the schema before being made to build model .

movieSchema.statics.findAllWithCreditCookies = function(callback) {
return this.find({ hasCreditCookie: true }, callback);
};

var Movie = Mongoose.model(‘Movie’, movieSchema);

// used on the static auxiliary function of the ‘Movie ‘ model compiled
Movie.findAllWithCreditCookies(function(err, movies) {
if (err) return console.error(err);
console.dir(movies);
});

That’s all you need to do to manipulate the data in MongoDB . Mongoose makes this very simple task so you can develop your services quickly . Using this along with your skills with Express , you can develop a very good and functional web application.

Below is a code using the concepts presented here that implements the static helper function to get all movies with ‘ credit cookies , saved 3 Thor movies with’ credit cookies and then creates a timeout to get the movies using the auxiliary function one second later – this is done because as we are working with non-blocking IO Node does not wait for the time to save the movies before proceeding , so we take some time to make sure they were saved before picking them up .
var Mongoose = require(‘Mongoose’);
var db = Mongoose.connection;

db.on(‘error’, console.error);
db.once(‘open’, function() {
// create your schemas and models here.
console.log(‘Connected.’)

var movieSchema = new Mongoose.Schema({
title: { type: String },
rating: String,
releaseYear: Number,
hasCreditCookie: Boolean
});

movieSchema.statics.findAllWithCreditCookies = function(callback) {
return this.find({ hasCreditCookie: true }, callback);
};

var Movie = Mongoose.model(‘Movie’, movieSchema);
for (var i =1; i<=3; i++){
var thor = new Movie({
title: ‘Thor ‘ + i,
rating: ‘PG-13’,
releaseYear: ‘2011’, // Note the use of String to Number of inves

hasCreditCookie: true
});

thor.save(function(err, thor) {
if (err) return console.error(err);
console.log(‘Salvo: ‘)
console.dir(thor);
});
}

setTimeout(function(){
// Utilizadno the static helper function model ‘Movie’ compiled
Movie.findAllWithCreditCookies(function(err, movies) {
if (err) return console.error(err);
console.log(‘Buscado: ‘)
console.dir(movies);
});
}, 1000);
});

Mongoose.connect(‘mongodb://localhost/test’);




LEAVE A REPLY

Please enter your comment!
Please enter your name here