The Mongoose Cheat Sheet

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

If you’re looking to use a MongoDB database with your web application running on NodeJS you might be looking at which npm libraries which will allow you to easily interact with MongoDB. Mongoose and MongoJS are the two top choices for developers in this scenario. In this article we’ll give a quick cheat sheet of the common commands you’ll use with the Mongoose library that will quickly get you up and running. We’ll show basic commands and a very quick briefing on what each command does.

  • Notes:
    • To demo we will use the example of creating a database for a small grocery store with a grocery products as the records.
    • Most of these functions have several optional parameters including a callback that we are choosing not to show here for the sake of simplicity.

Cheat Sheet

Setup

To get setup with Mongoose you’ll have to have mongoose installed from npm using

1
npm install mongoose

Then you’ll need it required in your models and any js file where you are using it

1
var mongoose = require("mongoose");

Schema

The big difference between MongoJS and Mongoose is that Mongoose pushes you to create documents using a schema. You define a schema then create documents using that schema. With MongoJS on the other hand you’re free to do whatever you’d like. Some people prefer the freedom of MongoJS and some people prefer the structure of Mongoose. Since this is the major differentiating point we’ll start with creating a schema.

To create a schema your js will look something like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var ProductSchema = new Schema({
 
  name: {
    type: String,
    required: true
  },
  brand: {
    type: String,
    required: false
  },
  order: {
    type: Schema.Types.ObjectId,
    ref: "Order"
  }
});

// This creates our model from the above schema, using mongoose's model method
var Product = mongoose.model("Product", ProductSchema);

// Export the Article model
module.exports = Product;

In this example we’ve created a simple schema that uses a couple primitive String fields “name” and “brand” but also an “order” field which could join with another Schema. This is like a Join in relational databases.

As you can see we create the schema, then create our model from that schema, then lastly we export that model so that our other javascript files can create documents using that model.

Creating documents based on the model

To use the model we need to import mongoose and the model. We have our model in a models folder so our code to do so looks like this

1
2
3
var mongoose = require("mongoose");
var db = require("./models");
mongoose.connect("mongodb://localhost:27017/grocerydb", { useNewUrlParser: true });

Then we create a document like so

1
2
3
4
5
6
7
8
var product = { name: "Soda", brand: "demoBrand" };
db.Product.create(product)
.then(function(dbProduct) {
    console.log(dbProduct);
})
.catch(function(err) {
    console.log(err);
});

We showed the .then() and .catch() for demonstration of how to handle success and failures but we will omit them in the future examples so we can solely concentrate on Mongoose commands.

Creating multiple documents `js db.Product.insertMany([{ name: ‘Soda’ }, { name: ‘Milk’}]); `

Finding documents

We can find all our documents (Products) with a command like below.

1
  db.Product.find({})

Find a document based on id

1
db.Product.findOne({ _id: <id> })

Updating

Update a single document

1
db.Product.updateOne({ name: 'Soda' }, { brand: 'newBrand' });

Update multiple documents

1
db.Product.updateMany({ brand: 'demoBrand' }, { quantity: 500 });

Delete Documents

Delete a single document

1
db.Product.deleteOne({ name: 'Soda' });

Delete multiple documents

1
db.Product.deleteMany({ quantity: { $gte: 100 } });

Conclusion

In this cheat sheet we gave you the basic CRUD ( Create, Read, Update, Delete ) commands that will be commonly used with Mongoose. Mongoose is a very easy library to get up and running with so get started and try out some commands. You can install Mongoose from npm by running npm install mongoose. We hope this cheat serves as a good introduction or as a reminder of how to use Mongoose within your NodeJS. If you have any feedback on commands we could add please don’t hesitate to reach out to us.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.