Skip to content

Instantly share code, notes, and snippets.

@tmurphree
Forked from subfuzion/mongoose-cheatsheet.md
Last active April 17, 2024 18:50
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmurphree/1a6a8f575b7309c478fac406f0e893b2 to your computer and use it in GitHub Desktop.
Save tmurphree/1a6a8f575b7309c478fac406f0e893b2 to your computer and use it in GitHub Desktop.
mongoose cheatsheet

Definitely not comprehensive. This is meant to be a basic memory aid with links to get more details. I'll add to it over time.

Install

$ npm install mongoose --save

Connect

const mongoose = require('mongoose');
const connectionString = process.env.MONGO_URI || 'mongodb://localhost/databasenamegoeshere';

//overwrite deprecated Mongoose promise
mongoose.Promise = global.Promise;

//connect to mongodb
mongoose.connect(connectionString, {useMongoClient: true})
  .then(() => {
    console.log('Connected to database at ', new Date().toLocaleString());
  })
  .catch((err) => {
    console.error('Error connecting to the database: ', err);
  });

Defining a schema

const userSchema = new mongoose.Schema({
  name: {
    first: String,
    last: { type: String, trim: true }
  },
  age: { type: Number, min: 0 },
  posts: [ { title: String, url: String, date: Date } ],
  updated: { type: Date, default: Date.now }
});
SchemaTypes
  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

SchemaTypes
SchemaType API
SchemaType#default
SchemaType#validate
get
set
select

Notes

Mixed types and dates that are modified using JavaScript Date methods are not hooked into mongoose change tracking logic. To save changes, let mongoose know about them using markModified('path') before calling save.

Instantiating a model

A model is a constructor compiled from a schema. Model instances represent documents.

    const User = mongoose.model('User', userSchema);

    var u = new User({
      name: {
        first: 'Tony',
        last: 'Pujals'
      },
      age: 99
    });

Query

The easiest way to query is to use Model.find, Model.findById, or Model.findOne methods.

These methods return a Query, which is not ideal. If you use the .exec() method one of the above, you get a Promise.

To update something, use a Promise chain and work on the result. The following code changes the name on one object with the name of 'Bob' to 'Sam':

MyModel.findOne({name: 'Bob'}).exec()
.then(function(data){
    data.name = 'Sam';
    return data.save();  //we need the return because .save() returns a Promise & we're in a 'then' already
    })
    .then(function() {
      //at this point the save is successful; we'd go to the catch otherwise
      res.status(204);   //use Express to send a response code
    })
    .catch(function(err) {
      console.error(err);
      res.status(400).json(err);  //use Express to send a response code
    });

You can also search on embedded documents: assuming you have a House where:

var HouseSchema = new mongoose.Schema({
    address: AddressSchema
});

var House = mongoose.model('House', HouseSchema);

House.findOne({'address.city': 'Tuscaloosa'}).exec();  

Assuming that the AddresseSchema has a field called 'city', 'address.city' looks for a House document where House.address.city is Tuscaloosa.

You can use .select to include and exclude fields: the following code selects the content, id, createdAt, and updatedAt fields and explicitly excludes the _id field by prefixing the field name with '-'. _id is automatically included by default unless explicitly excluded.

Joke.find().select('content id createdAt updatedAt -_id').exec()
  .then(function(data) {
    res.status(200).json(data);
  })
  .catch(function(err) {
    console.error(err);

    res.status(400).json(err);
  });

You could also use Joke.find().select('-_id -__v').exec(), which excludes the _id and __v fields and returns all other fields.

Queries overview Read this first

query objects in the API docs

$where
    query.$where('this.comments.length > 10 || this.name.length > 5')

    // or

    query.$where(function() {
      return this.comments.length > 10 || this.name.length > 5;
    });

mongoDB $where

$all

mongoose $all
mongoDB $all

$count

http://mongoosejs.com/docs/api.html#query_Query-count

$distinct

http://mongoosejs.com/docs/api.html#query_Query-distinct

#elemMatch

http://mongoosejs.com/docs/api.html#query_Query-elemMatch

#equals

http://mongoosejs.com/docs/api.html#query_Query-equals

#exec

http://mongoosejs.com/docs/api.html#query_Query-exec

#exists

http://mongoosejs.com/docs/api.html#query_Query-exists

#find

http://mongoosejs.com/docs/api.html#query_Query-find

#findById

Finds a single document by its _id field. findById(id) is almost equivalent to findOne({ _id: id }). If you want to query by a document's _id, use findById() instead of findOne().

http://mongoosejs.com/docs/api.html#model_Model.findById

#findByIdAndRemove

http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove

#findByIdAndUpdate

http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

findOne

When executed, the first found document is passed to the callback.

http://mongoosejs.com/docs/api.html#query_Query-findOne

findOneAndRemove

http://mongoosejs.com/docs/api.html#query_Query-findOneAndRemove

findOneAndUpdate

http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate

#gt

http://mongoosejs.com/docs/api.html#query_Query-gt

#gte

http://mongoosejs.com/docs/api.html#query_Query-gte

#hint

http://mongoosejs.com/docs/api.html#query_Query-hint

#in

http://mongoosejs.com/docs/api.html#query_Query-in

#lean

http://mongoosejs.com/docs/api.html#query_Query-lean

#limit

http://mongoosejs.com/docs/api.html#query_Query-limit

#lt

http://mongoosejs.com/docs/api.html#query_Query-lt

#lte

http://mongoosejs.com/docs/api.html#query_Query-lte

#maxScan

http://mongoosejs.com/docs/api.html#query_Query-maxScan

#merge

http://mongoosejs.com/docs/api.html#query_Query-merge

#mod

http://mongoosejs.com/docs/api.html#query_Query-mod

#ne

http://mongoosejs.com/docs/api.html#query_Query-ne

#nin

http://mongoosejs.com/docs/api.html#query_Query-nin

#nor

http://mongoosejs.com/docs/api.html#query_Query-nor

#or

http://mongoosejs.com/docs/api.html#query_Query-or

#populate

http://mongoosejs.com/docs/api.html#query_Query-populate

#read

http://mongoosejs.com/docs/api.html#query_Query-read

#regex

http://mongoosejs.com/docs/api.html#query_Query-regex

#remove
  • Removes all documents matching a query from a collection.

Ex.:

Album.remove({ artist: 'Anne Murray' }, callback);

  • To remove all documents in a collection (sort of like drop collection, except the collection exists afterwards):

Album.remove({}, callback);

?? this one ??

http://mongoosejs.com/docs/api.html#model_Model-collection

?? or this one ??

http://mongoosejs.com/docs/api.html#query_Query-remove

#save

Saves this document. Returns a Promise.

http://mongoosejs.com/docs/api.html#model_Model-save

#select

http://mongoosejs.com/docs/api.html#query_Query-select

#setOptions

http://mongoosejs.com/docs/api.html#query_Query-setOptions

#size

http://mongoosejs.com/docs/api.html#query_Query-size

#skip

http://mongoosejs.com/docs/api.html#query_Query-skip

#slice

http://mongoosejs.com/docs/api.html#query_Query-slice

#snapshot

http://mongoosejs.com/docs/api.html#query_Query-snapshot

#sort

http://mongoosejs.com/docs/api.html#query_Query-sort

#stream

http://mongoosejs.com/docs/api.html#query_Query-stream

#tailable

http://mongoosejs.com/docs/api.html#query_Query-tailable

#toConstructor

http://mongoosejs.com/docs/api.html#query_Query-toConstructor

#update

http://mongoosejs.com/docs/api.html#model_Model.update

http://mongoosejs.com/docs/api.html#query_Query-update

#where

http://mongoosejs.com/docs/api.html#query_Query-where

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment