Click here to close now.




















Welcome!

Blog Feed Post

Getting started with MongoDB and Mongoose

What is Mongoose?

Mongoose is an “elegant mongodb object modeling for node.js“. If you have used MongoDB before and tried basic database operations, you might have noticed that MongoDB is  “schema less”. When you are looking to implement a more structured database and want to leverage the power of MongoDB, Mongoose is one of the ODM (Object Data Mapping) solutions.

To quickly demonstrate, you run an insert command into a collection named users like


db.users.insert({ name : 'Arvind', gender : 'male'});

And right after that you can run


db.users.insert({ name : 'Arvind', gender : 'male', password : '!@#$'});

and MongoDB will never complain about the variation in the number of columns (key value pairs). This is very flexible. But when you want to keep your data more organized and structured, you would need to maintain that in your server code, writing validation, making sure nothing irrelevant is stored in a collection. And this is where Mongoose makes life easy.

“Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in type casting, validation, query building, business logic hooks and more, out of the box.”

Install Node js & MongoDB

To use Mongoose, we need to have Node js installed, you can find info here.

Start Developing

Let us first create a small playground, where we can have fun. Create a new folder named myMongooseApp. And open terminal/prompt here and run

npm init

This will help us in initializing a new node project. Fill it up as required. Next, we will install Mongoose as a dependency to our project. Run

npm install mongoose --save-dev

then start the MongoDB service by running

mongod

Next, create a new file named index.js at the root of the and then open it up in your favorite editor. And add the below code.

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myTestDB');

var db = mongoose.connection;

db.on('error', function (err) {
console.log('connection error', err);
});
db.once('open', function () {
console.log('connected.');
});

Here, we require the mongoose package to connect to the DB, and initialize the connection. The name of our Database is myTestDB.

Then run

node index.js

and you should see the connected message. You can also use a node package named nodemon for automatically restarting the node server on changes.
Now, our sandbox is ready to play!

Mongoose Schemas

Schemas are like skeletons. The bare bones of how your data collection will look like. If you are dealing with a collection of users, your schema would look something like this.

Name - String
Age - Number
Gender - String
Date of Birth - Date

And if you are dealing with a collection of products, your schema will look something like this

SKU - String
Name - String
Price - Number
InStock - Boolean
Quantity - Number

You can see the drift. When our data is guarded with a schema like this, the possibility of storing garbage data reduces drastically.

Now we got an understanding of schemas, lets try and build a user schema using Mongoose. Back to index.js and add the below code

var Schema = mongoose.Schema;
var userSchema = new Schema({
name : String,
age : Number,
DOB : Date,
isAlive : Boolean
});

Basic User related fields and their schema types. You can find a list of schema types here.

Next, we will create a model from the schema. Add

var User = mongoose.model('User', userSchema);

Thats it, our User model is ready. We will use this as our base schema to insert users into the database. This way we know that every document in a User collection will have the fields listed on the schema. Lets create a new user instance and save it to DB add

var arvind = new User({
name : 'Arvind',
age : 99,
DOB : '01/01/1915',
isAlive : true
});

arvind.save(function (err, data) {
if (err) console.log(err);
else console.log('Saved : ', data );
});

And you should see something like

Saved : { __v: 0,
name: 'Arvind',
age: 99,
DOB: Fri Jan 01 1915 00:00:00 GMT+0530 (IST),
isAlive: true,
_id: 536a4866dba434390d728216 }

No hassles, no issues. Simple and easy API to interact with Models.

Lets say that we want each model to have a method named isYounger. This method will return true if age is less than 50, false if greater. We can do this by querying the DB for the current user, then checking the conditioning and the returning true or false.

But what if we want to implement this method to all the models of User schema? This is how we do it in Mongoose

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myTestDB');

var db = mongoose.connection;

db.on('error', function (err) {
console.log('connection error', err);
});
db.once('open', function () {
console.log('connected.');
});

var Schema = mongoose.Schema;
var userSchema = new Schema({
name : String,
age : Number,
DOB : Date,
isAlive : Boolean
});

userSchema.methods.isYounger = function () {
return this.model('User').age < 50 ? true : false;
}

var User = mongoose.model('User', userSchema);

var arvind = new User({
name : 'Arvind',
age : 99,
DOB : '01/01/1915',
isAlive : true
});

arvind.save(function (err, data) {
if (err) console.log(err);
else console.log('Saved ', data );
});

console.log('isYounger : ',arvind.isYounger());

On line 21 we add the method definition. And the result on line 39 will be false. This is a simple handy way of adding methods to your Schema, making it more Object Oriented-ish.

In case you have a password field, you can add a method like encryptPassword(), to encrypt password and comparePassword(), to compare the passwords at login to the userSchema itself. You can read more about password Authentication here.

Out of box Mongoose also provides a few options when the schema is created. For example if you take a look at the below schema declaration, we are passing an option

var userSchema = new Schema({
name : String,
age : Number,
DOB : Date,
isAlive : Boolean
}, {strict : false});

strict:false. Strict option is true by default and it does not allow the ‘non-schema’ key value pairs to be saved. Example:

var arvind = new User({
name : 'Arvind',
age : 99,
DOB : '01/01/1915',
isAlive : true
});

will be saved, where as

var arvind = new User({
name : 'Arvind',
age : 99,
DOB : '01/01/1915',
isAlive : true,
bucketList : [{...}, {...}, {...} ]
});

All of the above will be saved minus the bucketList array, because it was not declared as part of schema. So, no client who consumes your services will be able to dump invalid data into your collections.

Another cool option is collection. If you don’t want your model name to be the same as collection name, you can pass the name as an option like

var userSchema = new Schema({
name : String,
age : Number,
DOB : Date,
isAlive : Boolean
}, {collection : 'appusers'});

You can find a list of other options here.

With Mongoose, You can also add events to your schemas like pre save or post save, where you can perform validations or process data or run other queries in the respective events. These methods are called as Middlewares.

A simple example can be a parallel middleware like

var userSchema = new Schema({
name : String,
age : Number,
DOB : Date,
isAlive : Boolean
})
schema.pre('save', true, function (next, done) {
// calling next kicks off the next middleware in parallel
next();
doAsync(done);
});

You can read more about middlewares here.

 

Thanks for reading. Do comment.
@arvindr21

Read the original blog entry...

More Stories By Dharshan Rangegowda

Dharshan is the founder of MongoDirector.com. Previous to MongoDirector Dharshan worked in the Virtualization and Data management groups in Microsoft.

Latest Stories
One of the hottest areas in cloud right now is DRaaS and related offerings. In his session at 16th Cloud Expo, Dale Levesque, Disaster Recovery Product Manager with Windstream's Cloud and Data Center Marketing team, will discuss the benefits of the cloud model, which far outweigh the traditional approach, and how enterprises need to ensure that their needs are properly being met.
Palerra, the cloud security automation company, announced enhanced support for Amazon AWS, allowing IT security and DevOps teams to automate activity and configuration monitoring, anomaly detection, and orchestrated remediation, thereby meeting compliance mandates within complex infrastructure deployments. "Monitoring and threat detection for AWS is a non-trivial task. While Amazon's flexible environment facilitates successful DevOps implementations, it adds another layer, which can become a ...
The speed of software changes in growing and large scale rapid-paced DevOps environments presents a challenge for continuous testing. Many organizations struggle to get this right. Practices that work for small scale continuous testing may not be sufficient as the requirements grow. In his session at DevOps Summit, Marc Hornbeek, Sr. Solutions Architect of DevOps continuous test solutions at Spirent Communications, explained the best practices of continuous testing at high scale, which is rele...
"We got started as search consultants. On the services side of the business we have help organizations save time and save money when they hit issues that everyone more or less hits when their data grows," noted Otis Gospodnetić, Founder of Sematext, in this SYS-CON.tv interview at @DevOpsSummit, held June 9-11, 2015, at the Javits Center in New York City.
Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world. Get ready to learn the facts: Is there a bias against women in the tech / developer communities? Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions? Some beginnings of what to do about it! In her Opening Keynote at 16th Cloud Expo, S...
With SaaS use rampant across organizations, how can IT departments track company data and maintain security? More and more departments are commissioning their own solutions and bypassing IT. A cloud environment is amorphous and powerful, allowing you to set up solutions for all of your user needs: document sharing and collaboration, mobile access, e-mail, even industry-specific applications. In his session at 16th Cloud Expo, Shawn Mills, President and a founder of Green House Data, discussed h...
Delphix, the market leader in Data as a Service (DaaS), has been announced winner of the DevOps Solution Award at the prestigious Computing Vendor Excellence Awards in London. The awards celebrate the achievements of the technology vendors and service providers that are leading the field of enterprise IT. Delphix was recognised as the vendor demonstrating the most effective support of DevOps culture for its ability to improve time to market and collaboration between teams.
"Our biggest growth area has been the security services, the managed services - the things that differentiate us in the market that there is no client that's too small and there's no client that's too big," explained Paul Mazzucco, Chief Security Officer at TierPoint, in this SYS-CON.tv interview at 16th Cloud Expo, held June 9-11, 2015, at the Javits Center in New York City.
The Cloud industry has moved from being more than just being able to provide infrastructure and management services on the Cloud. Enter a new era of Cloud computing where monetization’s services through the Cloud are an essential piece of strategy to feed your organizations bottom-line, your revenue and Profitability. In their session at 16th Cloud Expo, Ermanno Bonifazi, CEO & Founder of Solgenia, and Ian Khan, Global Strategic Positioning & Brand Manager at Solgenia, discussed how to easily o...
"We've just seen a huge influx of new partners coming into our ecosystem, and partners building unique offerings on top of our API set," explained Seth Bostock, Chief Executive Officer at IndependenceIT, in this SYS-CON.tv interview at 16th Cloud Expo, held June 9-11, 2015, at the Javits Center in New York City.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at @ThingsExpo, James Kirkland, Red Hat's Chief Arch...
Sysdig has announced two significant milestones in its mission to bring infrastructure and application monitoring to the world of containers and microservices: a $10.7 million Series A funding led by Accel and Bain Capital Ventures (BCV); and the general availability of Sysdig Cloud, the first monitoring, alerting, and troubleshooting platform specializing in container visibility, which is already used by more than 30 enterprise customers. The funding will be used to drive adoption of Sysdig Clo...
The Software Defined Data Center (SDDC), which enables organizations to seamlessly run in a hybrid cloud model (public + private cloud), is here to stay. IDC estimates that the software-defined networking market will be valued at $3.7 billion by 2016. Security is a key component and benefit of the SDDC, and offers an opportunity to build security 'from the ground up' and weave it into the environment from day one. In his session at 16th Cloud Expo, Reuven Harrison, CTO and Co-Founder of Tufin,...
The Internet of Things is not only adding billions of sensors and billions of terabytes to the Internet. It is also forcing a fundamental change in the way we envision Information Technology. For the first time, more data is being created by devices at the edge of the Internet rather than from centralized systems. What does this mean for today's IT professional? In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists addressed this very serious issue of pro...
"We do data integration for B2B also application to application, and we do data management and enable Big Data," explained Pat Adamiak, Vice President, Product Marketing at Liaison Technologies, in this SYS-CON.tv interview at 16th Cloud Expo, held June 9-11, 2015, at the Javits Center in New York City.