Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Mongoose for Application Development
Mongoose for Application Development

Mongoose for Application Development: Mongoose streamlines application development on the Node.js stack and this book is the ideal guide to both the concepts and practical application. From connecting to a database to re-usable plugins, it's all here.

eBook
€17.99 €25.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Mongoose for Application Development

Chapter 2. Establishing a Database Connection

We are going to look at the two methods Mongoose uses to connect to databases, mongoose.connect and createConnection. We will also go through various configuration options.

By the end of this chapter, you will understand how to best use the different Mongoose connection methods to meet your needs. We will also have added a connection to the MongoosePM example project.

Mongoose default connection


The way to set the default connection to a MongoDB database via Mongoose is nice and easy, using the mongoose.connect method.

var dbURI = 'mongodb://localhost/mydatabase';
mongoose.connect(dbURI);

This will open a Mongoose connection to the Mongo database mydatabase, running on the server localhost. If established at the correct place in your code, this connection will now be available at any point in your app, if you require Mongoose.

Tip

Best practice

The best practice for a default Mongoose database connection is to open it when the application starts, and keep it open to be re-used. The connection should only need to be closed if your app is being shut down or restarted.

Using multiple connections

The default connection is great if your app only needs to connect to one database. But what happens if you need to connect to a second database at the same time? Or connect to the same database as a different user with different permissions.

For this we can use the mongoose...

About the connection string


The connection string—dbURI in our examples—can use any of the options from the MongoDB connection string. We're not going to cover them all here, but here are a couple of common options.

Setting the port

The default port is 27017. If you wanted to specify a different port, say 27018, you would do so using the following code snippet:

var dbURI = 'mongodb://localhost:27018/mydatabase';

Specifying a database user

If you want to access the database as a particular user, you can add the username and password in front of the hostname.

var dbURI = 'mongodb://username:password@localhost/mydatabase';

Connection options


Mongoose allows you to pass certain options through to both connection methods. If specified, these options will override those set in the connection string.

The options are sent as a JSON object as an optional second parameter to the connection call. For example:

var dbURI = 'mongodb://localhost/mydatabase';
var dbOptions = {'user':'db_username','pass':'db_password'};
mongoose.connect(dbURI, dbOptions);

The options you can use this way are:

  • user and pass: Username and password for the database, if required and not specified in the connection string.

  • db: This relates to the DB options available in the Node MongoDB Native driver.

  • server: This relates to the server options available in the Node MongoDB Native driver.

  • replset: This option allows you to specify a ReplicaSet. The details of ReplicaSet methods are beyond the scope of this book, but the principle is that you can have one primary database where all the writes are made to, and multiple secondary databases. If the...

Closing the connection


As we have already seen, the general best practice is to open your connection at application start up, and keep it open. However, there are times when you will want to close the connection. For example, if your application is shutting down, or restarting, the database connection needs to be manually closed, or if you are running a single-hit script rather than a persistent application.

Calling the close command

Each Mongoose connection has a close() method that takes an optional callback function.

If you are using the default connection you call it like the following code snippet does:

mongoose.connection.close(function () {
  console.log('Mongoose default connection closed');
});

Calling the close() method on a named connection is just as easy, using our example from earlier:

adminConnection.close(function () {
  console.log('Mongoose connection adminConnection closed');
});

Closing when the Node process ends

As a rule you should tidy up the connections when your Node application...

Connection events


The connection process in Mongoose inherits the Node EventEmitter class, meaning that we can set certain code to run following specific events. We can—and will—work with some of the connection events, such as connected, disconnected, and error.

The connection events are all used in the same way, sending a callback to the connection.on event listener. For example, if we wanted to log to the console when a connection error occurs we could do this in the following code:

mongoose.connection.on('error',function (err) {
  console.log('Mongoose connection error: ' + err);
});

Connecting our project


Now we know what we're doing, let's connect our project to a database using the default Mongoose connection.

Creating the connection

For the sake of well organized code, let's create a folder called model, and in that, an empty JavaScript file called db.js. We'll use this for managing the Mongoose connection, and will add to it in later chapters.

At this stage the file needs to do three things:

  1. Bring in the Mongoose module

  2. Build the connection string for the database

  3. Open the Mongoose connection to the database

So in your /model/db.js file, enter the following:

// Bring Mongoose into the project
var mongoose = require( 'mongoose' );

// Build the connection string
var dbURI = 'mongodb://localhost/MongoosePM';

// Create the database connection
mongoose.connect(dbURI);

Each of the three objectives is achieved with just one line of code—pretty simple don't you think!

Catching the events

Next up we want to set up our event handlers. At this stage, we are just going to log messages...

Summary


In this chapter, we have looked at the two methods of creating a Mongoose connection to a MongoDB database, and when you would use each method.

We have learned that the best practice is to create a connection when your application starts and keep it open to be re-used. Tied to this we have seen how and when to close the connection, and how to act upon events emitted by the connection process.

We have also taken a brief look at how to specify different options if you have a more complex database setup, or want to override some defaults.

You should now have connected your MongoosePM project to the MongoosePM database, even though the database doesn't exist yet!

In the next chapter, we're going to start getting stuck into the real meat of Mongoose, by defining schemas and models.

Left arrow icon Right arrow icon

Key benefits

  • Rapid application development with Mongoose on the Node.js stack
  • Use Mongoose to give structure and manageability to MongoDB data
  • Practical exampless on how to use Mongoose for CRUD operations
  • Provides a number of helpful tips and takes away the complexity of everyday MongoDB operations
  • Walks you through building a project management application using Mongoose, Node.js, MongoDB, and Express

Description

Mongoose is all about putting the data model where it should be: in your application. You can control everything from within your application in JavaScript, eliminating the need to work with the database or a separate management system. Mongoose for Application Development is a practical, hands-on guide that takes you from installing the technology stack through the steps of developing a web application. It covers the key features of Mongoose and how to use them to rapidly develop a Node.js and MongoDB application. This book introduces the full technology stack of Node.js, MongoDB, Express, and Mongoose. It will take you through the process of building an application on this stack with a focus on how Mongoose makes the process quicker and easier. You will see how Mongoose removes a layer of complexity when dealing with MongoDB whilst giving you more control over your data from your application. You will learn how to define schemas and models for your data in JavaScript. Using these schemas and models, you will learn how to build the cornerstone of any web application that will include CRUD operations (creating, reading, updating, and deleting data). If you want to learn how to build applications quickly and efficiently using Node.js, then Mongoose and this book are ideal for you. Using practical examples throughout, Mongoose for Application Development not only teaches you about the concepts of Mongoose, but walks through how to use them to build a real-life application.

Who is this book for?

This book is ideal for people who want to develop applications on the Node.js stack quickly and efficiently. Prior knowledge of the stack is not essential as the book briefly covers the installation of the core components and builds all aspects of the example application. The focus of the book is on what Mongoose adds to you applications, so experienced Node.js developers will also benefit.

What you will learn

  • Learn the different methods of using Mongoose to connect to a database
  • Learn to define schemas and building data models
  • Interact with data using schema methods
  • Create databases, collections, and data
  • Query the database to find specific data
  • Edit, save, and delete data
  • Validate data using Mongoose validators
  • Use population to link datasets
  • Use sub-documents and nested schemas to provide data depth
  • Get to grips with code efficiency through re-usable plugins

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 26, 2013
Length: 142 pages
Edition : 1st
Language : English
ISBN-13 : 9781782168195
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Aug 26, 2013
Length: 142 pages
Edition : 1st
Language : English
ISBN-13 : 9781782168195
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 107.97
Express Web Application Development
€41.99
Mongoose for Application Development
€32.99
Advanced Express Web Application Development
€32.99
Total 107.97 Stars icon

Table of Contents

11 Chapters
Introducing Mongoose to the Technology Stack Chevron down icon Chevron up icon
Establishing a Database Connection Chevron down icon Chevron up icon
Schemas and Models Chevron down icon Chevron up icon
Interacting with Data – an Introduction Chevron down icon Chevron up icon
Interacting with Data – Creation Chevron down icon Chevron up icon
Interacting with Data – Reading, Querying, and Finding Chevron down icon Chevron up icon
Interacting with Data – Updating Chevron down icon Chevron up icon
Interacting with Data – Deleting Chevron down icon Chevron up icon
Validating Data Chevron down icon Chevron up icon
Complex Schemas Chevron down icon Chevron up icon
Plugins – Re-using Code Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(10 Ratings)
5 star 50%
4 star 20%
3 star 30%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Alex B Jul 14, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Amazing book. There are a lot of tips and tricks in there and if you use mongoose a lot you will actually find a lot of cool coding secrets and explanations to weird things that go on under the hood. Its a must read if you like Mongoose.
Amazon Verified review Amazon
CharlieBear Apr 30, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is an excellent book for anyone moving from C#/.NET or any other non-web based development platform. It is a great way to get a quick start if you want to jump onto the Javascript bandwagon and get ready for web apps that run and behave like Windows apps.The book covers everything you need to build a browser based application (or mobile apps too) with all code being Javascript. The examples are easy to follow and to the point, including the traditional CRUD application. Routes, Jade templates, JSON, AJAX, data validation and plugins are all also covered. It's just a good book to get started writing client and server side applications. Also covers a lot of the different methods for fetching and working with data. Mongoose has a "code first" database creation feature that is very cool.There is one problem due to changes made to Node.js launch for Express/Mongoose since the date of publication. I'd recommend skipping the getting started instructions in the book (chapter 1) and use this web site instead, especially if you are running with MS Windows:[...]I found the above URL after following the book's instructions, step-by-step (using Windows 7) and couldn't get Express to fire up. Other than that, I'd recommend using this book for anyone who wants to get started writing highly responsive web based/mobile applications.
Amazon Verified review Amazon
Robby May 07, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book helped me a lot. It's small, to the point. The code works. It got me up to speed. Good job
Amazon Verified review Amazon
Konstantin Sep 26, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought this book from the publishers site to help me get up to speed with using Mongoose, Node.js, MongoDB, and Express. I must say i am very impressed with it. The book is very well written, and the examples work as expected. (unlike other programming books you buy). The sample project in the book comes in very handy and teaches you how to build a CRUD like application using these technology stack. Note that the major focus on this book is mongoose! Though you get to understand how the other stack work, they are not in-depth. Mongoose however is cover pretty deeply.
Amazon Verified review Amazon
Eric Rabbath May 02, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is an excellent short book on using Mongoose to connect your MongoDB back-end database to your Node.js application. The explanations are very clear and to the point, and the examples given are always an excellent illustration of the point being discussed.The ongoing example is also well chosen, and well used to integrate the various concepts into a complete working application. It uses Express to build the application, and while the explanations in the book are very clear and complete, a basic understanding of the key concepts of the Express framework (routes, request, response objects) is useful to really understand what is going on.As mentioned by others, the installation instructions are a little out of date, but this can very easily be solved with a simple web search.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.