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
Large scale deployments present unique planning challenges, system commissioning hurdles between IT and OT and demand careful system hand-off orchestration. In his session at @ThingsExpo, Jeff Smith, Senior Director and a founding member of Incenergy, will discuss some of the key tactics to ensure delivery success based on his experience of the last two years deploying Industrial IoT systems across four continents.
With the proliferation of both SQL and NoSQL databases, organizations can now target specific fit-for-purpose database tools for their different application needs regarding scalability, ease of use, ACID support, etc. Platform as a Service offerings make this even easier now, enabling developers to roll out their own database infrastructure in minutes with minimal management overhead. However, this same amount of flexibility also comes with the challenges of picking the right tool, on the right ...
With over 720 million Internet users and 40–50% CAGR, the Chinese Cloud Computing market has been booming. When talking about cloud computing, what are the Chinese users of cloud thinking about? What is the most powerful force that can push them to make the buying decision? How to tap into them? In his session at 18th Cloud Expo, Yu Hao, CEO and co-founder of SpeedyCloud, answered these questions and discussed the results of SpeedyCloud’s survey.
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
DevOps at Cloud Expo – being held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Am...
"This week we're really focusing on scalability, asset preservation and how do you back up to the cloud and in the cloud with object storage, which is really a new way of attacking dealing with your file, your blocked data, where you put it and how you access it," stated Jeff Greenwald, Senior Director of Market Development at HGST, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
The 19th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Digital Transformation, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportuni...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develo...
“We're a global managed hosting provider. Our core customer set is a U.S.-based customer that is looking to go global,” explained Adam Rogers, Managing Director at ANEXIA, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
Basho Technologies has announced the latest release of Basho Riak TS, version 1.3. Riak TS is an enterprise-grade NoSQL database optimized for Internet of Things (IoT). The open source version enables developers to download the software for free and use it in production as well as make contributions to the code and develop applications around Riak TS. Enhancements to Riak TS make it quick, easy and cost-effective to spin up an instance to test new ideas and build IoT applications. In addition to...
Predictive analytics tools monitor, report, and troubleshoot in order to make proactive decisions about the health, performance, and utilization of storage. Most enterprises combine cloud and on-premise storage, resulting in blended environments of physical, virtual, cloud, and other platforms, which justifies more sophisticated storage analytics. In his session at 18th Cloud Expo, Peter McCallum, Vice President of Datacenter Solutions at FalconStor, discussed using predictive analytics to mon...
IoT is rapidly changing the way enterprises are using data to improve business decision-making. In order to derive business value, organizations must unlock insights from the data gathered and then act on these. In their session at @ThingsExpo, Eric Hoffman, Vice President at EastBanc Technologies, and Peter Shashkin, Head of Development Department at EastBanc Technologies, discussed how one organization leveraged IoT, cloud technology and data analysis to improve customer experiences and effi...
Internet of @ThingsExpo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 19th International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world and ThingsExpo Silicon Valley Call for Papers is now open.
"We've discovered that after shows 80% if leads that people get, 80% of the conversations end up on the show floor, meaning people forget about it, people forget who they talk to, people forget that there are actual business opportunities to be had here so we try to help out and keep the conversations going," explained Jeff Mesnik, Founder and President of ContentMX, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Isomorphic Software will exhibit at DevOps Summit at 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Isomorphic Software provides the SmartClient HTML5/AJAX platform, the most advanced technology for building rich, cutting-edge enterprise web applications for desktop and mobile. SmartClient combines the productivity and performance of traditional desktop software with the simp...