Skip to content

Instantly share code, notes, and snippets.

@edoves
Last active October 30, 2024 14:47
Show Gist options
  • Select an option

  • Save edoves/aba3a78a992d63c5fea47efef5300d3c to your computer and use it in GitHub Desktop.

Select an option

Save edoves/aba3a78a992d63c5fea47efef5300d3c to your computer and use it in GitHub Desktop.
MongoDB and Mongoose Cheatsheet

MongoDB and Mongoose Cheatsheet

Beautifully-designed print-ready PDF

MongoDB

  • $ mongod: start MongoDB server (localhost:27017)
  • $ mongo: open MongoDB console (connect to local server by default)

MongoDB Console

  • > show dbs: show databases on the server
  • > use DB_NAME: select database DB_NAME
  • > show collections: show collections in the selected database
  • > db.COLLECTION_NAME.find(): perform the find query on collection with the COLLECTION_NAME name to find any items
  • > db.COLLECTION_NAME.find({"_id": ObjectId("549d9a3081d0f07866fdaac6")}): perform the find query on collection with the COLLECTION_NAME name to find item with ID 549d9a3081d0f07866fdaac6
  • > db.COLLECTION_NAME.find({"email": /gmail/}): perform the find query on collection with the COLLECTION_NAME name to find items with email property matching /gmail
  • > db.COLLECTION_NAME.update(QUERY_OBJECT, SET_OBJECT): perform the update query on collection with the COLLECTION_NAME name to update items that match QUERY_OBJECT with SET_OBJECT
  • > db.COLLECTION_NAME.remove(QUERY_OBJECT): perform remove query for items matching QUERY_OBJECT criteria on the COLLECTION_NAME collection
  • > db.COLLECTION_NAME.insert(OBJECT): add OBJECT to the collection with the COLLECTION_NAME name

Mongoose Installation

  • $ sudo npm install mongoose: install the latest Mongoose locally`
  • $ sudo npm install mongoose@3.8.20 --save: install Mongoose v3.8.20 locally and save to package.json

Mongoose Basic Usage

var mongoose = require('mongoose')
var dbUri = 'mongodb://localhost:27017/api'
var dbConnection = mongoose.createConnection(dbUri)
var Schema = mongoose.Schema
var postSchema = new Schema ({
  title: String,
  text: String
})
var Post = dbConnection.model('Post', postSchema, 'posts')
Post.find({},function(error, posts){
  console.log(posts)
  process.exit(1)
})

Mongoose Schema

  • String
  • Boolean
  • Number
  • Date
  • Array
  • Buffer
  • Schema.Types.Mixed
  • Schema.Types.ObjectId

Create, Read, Update, Delete (CRUD) Mongoose Example

// Create
var post = new Post({title: 'a', text: 'b')
post.save(function(error, document){
  ...
})


// Read
Post.findOne(criteria, function(error, post) {
  ...
})

// Update
Post.findOne(criteria, function(error, post) {
  post.set()
  post.save(function(error, document){
    ...
  })
})

// Delete
Post.findOne(criteria, function(error, post) {
  post.remove(function(error){
    ...
  })
})

Mongoose Model Methods

  • find(criteria, [fields], [options], [callback]): find document; callback has error and documents arguments
  • count(criteria, [callback])): return a count; callback has error and count arguments
  • findById(id, [fields], [options], [callback]): return a single document by ID; callback has error and document arguments
  • findByIdAndUpdate(id, [update], [options], [callback]): executes MongoDB's findAndModify to update by ID
  • findByIdAndRemove(id, [options], [callback]): executes MongoDB's findAndModify to remove
  • findOne(criteria, [fields], [options], [callback]): return a single document; callback has error and document arguments
  • findOneAndUpdate([criteria], [update], [options], [callback]): executes MongoDB's findAndModify to update
  • findOneAndRemove(id, [update], [options], [callback]): executes MongoDB's findAndModify to remove
  • update(criteria, update, [options], [callback]): update documents; callback has error, and count arguments
  • create(doc(s), [callback]): create document object and save it to database; callback has error and doc(s) arguments
  • remove(criteria, [callback]): remove documents; callback has error argument

Mongoose Document Methods

  • save([callback]): save the document; callback has error, doc and count arguments
  • set(path, val, [type], [options]): set value on the doc's property
  • get(path, [type]): get the value
  • isModified([path]): check if the property has been modified
  • populate([path], [callback]): populate reference
  • toJSON(options): get JSON from document
  • validate(callback): validate the document

Query Helpers

animalSchema.query.byName = function(name) {
  return this.where({ name: new RegExp(name, 'i') });
};

var Animal = mongoose.model('Animal', animalSchema);

Animal.find().byName('fido').exec(function(err, animals) {
  console.log(animals);
});

Animal.findOne().byName('fido').exec(function(err, animal) {
  console.log(animal);
});

Indexes

var animalSchema = new Schema({
  name: String,
  type: String,
  tags: { type: [String], index: true } // field level
});

animalSchema.index({ name: 1, type: -1 }); // schema level

Mongoose Operations Cheat sheet

Schema

Types

SchemaTypes
  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array
const UserSchema = new mongoose.Schema({
fullname: {
  type: String, // Data Type
  min:6,
  max:12,
  required: [true, "Please enter your fullname"], // Required with error
  trim: true,
},
followersCount: {
  type: Number,
  default: 0,
},
followers: [{ type: mongoose.Schema.ObjectId, ref: "User" }], // Array of Object Ids and ref to schema
createdAt: {
  type: Date,
  default: Date.now,
},
drink: {
  type: String,
  enum: ['Coffee', 'Tea', 'Water',]
}
}

module.exports = mongoose.model("User", UserSchema);

Queries are not promises

Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. If you need a fully-fledged promise, use the .exec() function.

const query = Band.findOne({name: "Guns N' Roses"});
assert.ok(!(query instanceof Promise));

// A query is not a fully-fledged promise, but it does have a `.then()`.
query.then(function (doc) {
// use doc
});

// `.exec()` gives you a fully-fledged promise
const promise = query.exec(); //or use await on promise
assert.ok(promise instanceof Promise);

promise.then(function (doc) {
// use doc
});

Methods

Mongoose Model Methods

  • find(criteria, [fields], [options], [callback]): find document; callback has error and documents arguments
  • count(criteria, [callback])): return a count; callback has error and count arguments
  • findById(id, [fields], [options], [callback]): return a single document by ID; callback has error and document arguments
  • findByIdAndUpdate(id, [update], [options], [callback]): executes MongoDB’s findAndModify to update by ID
  • findByIdAndRemove(id, [options], [callback]): executes MongoDB’s findAndModify to remove
  • findOne(criteria, [fields], [options], [callback]): return a single document; callback has error and document arguments
  • findOneAndUpdate([criteria], [update], [options], [callback]): executes MongoDB’s findAndModify to update
  • findOneAndRemove(id, [update], [options], [callback]): executes MongoDB’s findAndModify to remove
  • update(criteria, update, [options], [callback]): update documents; callback has error, and count arguments
  • create(doc(s), [callback]): create document object and save it to database; callback has error and doc(s) arguments
  • remove(criteria, [callback]): remove documents; callback has error argument

Examples

// ---------------------------------- Find -----------------------------------------
User.find({ author : bob._id }).exec()
// ------------------------------- Find in list --------------------------------------------
User.find()
    .where("_id")
    .in(following.concat([req.user.id]))
    .exec();
// -------------------------------Find and Populate--------------------------------------------
Post.find()
    .populate({
      path: "comments",
      select: "text",
      populate: { path: "user", select: "avatar fullname username" },  // Two level populate
    })
    .populate({ path: "user", select: "avatar fullname username" })
    .sort("-createdAt")
    .where("_id")
    .in(postIds)
    .lean()   // Lean menas POJO
    .exec();
// ------------------------------  Find Regex ---------------------------------------------
  const regex = new RegExp(req.query.username, "i");
  const users = await User.find({ username: regex });
// -------------------------------- Find One -------------------------------------------
User.findOne({ title: 'Bob goes sledding' })
	.select("-password")
  .populate('author')
  .exec()
// --------------------------------Find by Id -------------------------------------------
User.findById(bob._id)
.populate({ path: "posts", select: "files commentsCount likesCount" })
    .populate({ path: "savedPosts", select: "files commentsCount likesCount" })
    .populate({ path: "followers", select: "avatar username fullname" })
    .populate({ path: "following", select: "avatar username fullname" })
    .lean()  //Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO (So you cannot use Save() and other document methods)
    .exec();
// --------------------------------Find By Id and update -------------------------------------------
User.findByIdAndUpdate(req.params.id, {
    $push: { followers: req.user.id },
    $inc: { followersCount: 1 },
  });

// -----------------------------Find by Id and Update with options -------------------------------------
User.findByIdAndUpdate(
    req.user.id,
    {
      $set: { ...fieldsToUpdate, website, bio },
    },
    {
      new: true,
      runValidators: true,
    }
  ).select("avatar username fullname email bio website");

// ----------------------------Find and Pull ----------------------------------------------
User.findByIdAndUpdate(req.user.id, {
    $pull: { posts: req.params.id },
    $inc: { postCount: -1 },
  });


// -------------------------------Find and Populate exec -----------------------------------------
  let post = await Post.create({ caption, files, tags, user });

  await User.findByIdAndUpdate(req.user.id, {
    $push: { posts: post._id },
    $inc: { postCount: 1 },
  });

  post = await post
    .populate({ path: "user", select: "avatar username fullname" })
    .execPopulate(); // execPopulate is used to explicitly execute populate on query

Mongoose Document Methods

  • save([callback]): save the document; callback has error, doc and count arguments
  • set(path, val, [type], [options]): set value on the doc’s property
  • get(path, [type]): get the value
  • isModified([path]): check if the property has been modified
  • populate([path], [callback]): populate reference
  • toJSON(options): get JSON from document
  • validate(callback): validate the document
/ ---------------------------------------------------------------------------
  let post = await Post.create({ caption, files, tags, user });

  await User.findByIdAndUpdate(req.user.id, {
    $push: { posts: post._id },
    $inc: { postCount: 1 },
  });

  post = await post
    .populate({ path: "user", select: "avatar username fullname" })
    .execPopulate(); // execPopulate is used to explicitly execute populate on query

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