Getting Started

First be sure you have MongoDB and Node.js installed.

Next install Mongoose from the command line using npm:

  1. $ npm install mongoose --save

Now say we like fuzzy kittens and want to record every kitten we ever meet in MongoDB. The first thing we need to do is include mongoose in our project and open a connection to the test database on our locally running instance of MongoDB.

  1. // getting-started.js
  2. const mongoose = require('mongoose');
  3. mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});

We have a pending connection to the test database running on localhost. We now need to get notified if we connect successfully or if a connection error occurs:

  1. const db = mongoose.connection;
  2. db.on('error', console.error.bind(console, 'connection error:'));
  3. db.once('open', function() {
  4. // we're connected!
  5. });

Once our connection opens, our callback will be called. For brevity, let’s assume that all following code is within this callback.

With Mongoose, everything is derived from a Schema. Let’s get a reference to it and define our kittens.

  1. const kittySchema = new mongoose.Schema({
  2. name: String
  3. });

So far so good. We’ve got a schema with one property, name, which will be a String. The next step is compiling our schema into a Model.

  1. const Kitten = mongoose.model('Kitten', kittySchema);

A model is a class with which we construct documents. In this case, each document will be a kitten with properties and behaviors as declared in our schema. Let’s create a kitten document representing the little guy we just met on the sidewalk outside:

  1. const silence = new Kitten({ name: 'Silence' });
  2. console.log(silence.name); // 'Silence'

Kittens can meow, so let’s take a look at how to add “speak” functionality to our documents:

  1. // NOTE: methods must be added to the schema before compiling it with mongoose.model()
  2. kittySchema.methods.speak = function () {
  3. const greeting = this.name
  4. ? "Meow name is " + this.name
  5. : "I don't have a name";
  6. console.log(greeting);
  7. }
  8. const Kitten = mongoose.model('Kitten', kittySchema);

Functions added to the methods property of a schema get compiled into the Model prototype and exposed on each document instance:

  1. const fluffy = new Kitten({ name: 'fluffy' });
  2. fluffy.speak(); // "Meow name is fluffy"

We have talking kittens! But we still haven’t saved anything to MongoDB. Each document can be saved to the database by calling its save method. The first argument to the callback will be an error if any occurred.

  1. fluffy.save(function (err, fluffy) {
  2. if (err) return console.error(err);
  3. fluffy.speak();
  4. });

Say time goes by and we want to display all the kittens we’ve seen. We can access all of the kitten documents through our Kitten model.

  1. Kitten.find(function (err, kittens) {
  2. if (err) return console.error(err);
  3. console.log(kittens);
  4. })

We just logged all of the kittens in our db to the console. If we want to filter our kittens by name, Mongoose supports MongoDBs rich querying syntax.

  1. Kitten.find({ name: /^fluff/ }, callback);

This performs a search for all documents with a name property that begins with “fluff” and returns the result as an array of kittens to the callback.

Congratulations

That’s the end of our quick start. We created a schema, added a custom document method, saved and queried kittens in MongoDB using Mongoose. Head over to the guide, or API docs for more.