MongoDB and Mongoose Cheatsheet

Reference

Mongoose APIs
Mongoose Query APIs
Cheat Sheet

MongoDB

  1. $mongod : start MongoDB server (localhost:27017)
  2. $mongo : open MongoDB console (connect to local server by default)
  3. MongoDB Console

  4. show dbs : show databases on the server
  5. use DB_NAME : select database DB_NAME
  6. show collections : show collections in the selected database
  7. db.COLLECTION_NAME.find() : perform the find query on collection with the COLLECTION_NAME name to find any items
  8. db.COLLECTION_NAME.find({“_id” : ObjectId(“549d9a3081d0f07866fdaac6”)}) : perform the find query on collection with the COLLECTION_NAME name to find item with ID 549d9a3081d0f07866fdaac6
  9. 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
  10. 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
  11. db.COLLECTION_NAME.remove(QUERY_OBJECT) : perform remove query for items matching QUERY_OBJECT criteria on the COLLECTION_NAME collection
  12. db.COLLECTION_NAME.insert(OBJECT) : add OBJECT to the collection with the COLLECTION_NAME name
    Mongoose Installation
  13. $sudo npm install mongoose : install the latest Mongoose locally`
  14. $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

  1. String
  2. Boolean
  3. Number
  4. Date
  5. Array
  6. Buffer
  7. Schema.Types.Mixed
  8. 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

  1. find(criteria, [fields], [options], [callback]) : find document; callback has error and documents arguments
  2. count(criteria, [callback])) : return a count; callback has error and count arguments
  3. findById(id, [fields], [options], [callback]) : return a single document by ID; callback has error and document arguments
  4. findByIdAndUpdate(id, [update], [options], [callback]) : executes MongoDB’s findAndModify to update by ID
  5. findByIdAndRemove(id, [options], [callback]) : executes MongoDB’s findAndModify to remove
  6. findOne(criteria, [fields], [options], [callback]) : return a single document; callback has error and document arguments
  7. findOneAndUpdate([criteria], [update], [options], [callback]) : executes MongoDB’s findAndModify to update
  8. findOneAndRemove(id, [update], [options], [callback]) : executes MongoDB’s findAndModify to remove
  9. update(criteria, update, [options], [callback]) : update documents; callback has error, and count arguments
  10. create(doc(s), [callback]) : create document object and save it to database; callback has error and doc(s) arguments
  11. remove(criteria, [callback]) : remove documents; callback has error argument

    Mongoose Document Methods

  12. save([callback]) : save the document; callback has error, doc and count arguments
  13. set(path, val, [type], [options]) : set value on the doc’s property
  14. get(path, [type]) : get the value
  15. isModified([path]) : check if the property has been modified
  16. populate([path], [callback]) : populate reference
  17. toJSON(options) : get JSON from document
  18. 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:tring,
   type:String,
   tags:{ type :  [String], index :  true } // field level
 });

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

Leave a Reply

Your email address will not be published. Required fields are marked *