Xervo

Node.js and MongoDB - Getting Started with Mongoose

Node.js and MongoDB - Getting Started with Mongoose

Mongoose is a Node.js library that provides MongoDB object mapping similar to ORM with a familiar interface within Node.js. If you aren't familiar with Object Relational Mapping (ORM) or, Object Data Mapping (ODM) in the case of Mongoose, this means is that Mongoose translates data in the database to JavaScript objects for use in your application. Let's take a look at creating and storing documents in a collection using MongoDB and Mongoose.

Note: this post assumes you have Node.js and MongoDB installed. You must have MongoDB running in order to run the provided examples.

Connecting to MongoDB

For this post, we will be connecting to the test database that MongoDB defaults to when you start up the shell. We'll also make sure that any connection errors are written to the console. Note the use of the open event - this is where you will create schemas and compile models.

var mongoose = require('mongoose');

var db = mongoose.connection;

db.on('error', console.error);
db.once('open', function() {
  // Create your schemas and models here.
});

mongoose.connect('mongodb://localhost/test');

Schemas and Models

To begin, we will need a schema and a model in order to 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 be making a database of movies to keep track of which movies have credit cookies (post-credit scenes). Let's start off by creating a Movie schema and model.

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

// Compile a 'Movie' model using the movieSchema as the structure.
// Mongoose also creates a MongoDB collection called 'Movies' for these documents.
var Movie = mongoose.model('Movie', movieSchema);

Notice that the Movie model is capitalized, this is because when a model is compiled, the result is a constructor function that is used to create instances of the model. The instances created from the model constructor are documents which will be persisted by Mongo.

Create, Retrieve, Update, and Delete (CRUD)

Creating a new Movie document is easy now that you have defined the model, just instantiate a Movie model. Updating and saving is equally easy, make your changes then call the save function on your document.

var thor = new Movie({
  title: 'Thor'
, rating: 'PG-13'
, releaseYear: '2011'  // Notice the use of a String rather than a Number - Mongoose will automatically convert this for us.
, hasCreditCookie: true
});

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

The save function will provide the newly created document, you can see this in what is logged to the console.

{
  "title": "Thor",
  "rating": "PG-13",
  "releaseYear": 2011,
  "hasCreditCookie": true,
  "_id": "519a979e918d4d0000000001",
  "__v": 0
}

Retrieving an existing document is done in a couple of different ways. You can find documents based on any property from the schema and you can find any number of documents - use findOne to narrow the results to a single document.

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

// Find all movies.
Movie.find(function(err, movies) {
  if (err) return console.error(err);
  console.dir(movies);
});

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

Mongoose also allows you to easily create static helper functions for finding data.

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

// Use the helper as a static function of the compiled Movie model.
Movie.findAllWithCreditCookies(function(err, movies) {
  if (err) return console.error(err);
  console.dir(movies);
});

That's all it takes to CRUD data from MongoDB - Mongoose makes it dead simple so you can start building services quickly. Using this, along with your Express skills, you can build a pretty nice web app for tracking movies with credit cookies.

What is Xervo?

Xervo makes deploying applications in the public cloud or your own data center easy. Node.js, PHP, Java, Python, Nginx, and MongoDB supported. Full Docker support included in Enterprise version. It’s free to get started.

Share This Article

comments powered by Disqus