📖
Maissen's Grimoire
  • Maissen's Grimoire
  • Html and css grimoire
    • HTML5 Periodical Table
    • HTML Cheat Sheet
    • CSS Cheatsheets
  • Javascript Grimoire
    • JavaScript Cheat Sheet
      • Javascript Array in depth
      • Tagged Template Literals
      • Guard Clauses - The Best Way To Write Complex Conditional Logic
      • JavaScript Optional Chaining
      • JavaScript Null Coalesce
      • What Are Magic Numbers And Why Are They Bad
      • ES6/ECMAScript2015 Cheatsheet
      • First-class and Higher Order Functions: Effective Functional JavaScript
    • Useful JavaScript Tips, Tricks and Best Practices
    • Bits of code
    • Useful JavaScript libraries
      • Components
      • Animation
      • Maps
      • Helpers
      • Presentations
      • Charts
      • Games
      • Audio
      • Images
      • Video
    • Js the right way
  • Angular Grimoire
    • Angular doc
    • Getting Started
    • Angular clean architecture
    • Angular Cheat Sheet
    • TypeScript Cheat Sheet
    • My Favorite Tips and Tricks in Angular
    • NgRx: tips & tricks
    • Bits of code
      • Execute Multiple HTTP Requests in Angular
      • Authentification
        • Angular 8 JWT Authentication with HttpInterceptor and Router
      • Integrations
        • Spring Boot
          • Rest Example
            • Angular,Spring Boot,Spring Data and Rest Example(CRUD)
          • Authentification
            • Angular, Spring Boot: JWT Authentication with Spring Security example
            • Angular Spring Boot Security Oauth2
              • Spring Boot OAUTH2 Role-Based Authorization
              • Spring Boot Security Google Oauth
              • Spring Security OAuth2 User Registration
    • Most used dependency
  • Node Grimoire
    • Express.js 4 Cheatsheet
    • Useful Dependencies
    • How To Use And Write Express Middleware
    • Node.js with SQL databases
      • Node.js Token Based Authentication & Authorization example
      • Node.js Rest APIs example with Express, Sequelize & MySQL
      • Node.js Express & PostgreSQL: CRUD Rest APIs example with Sequelize
      • Sequelize
        • Sequelize Many-to-Many Association example – Node.js & MySQL
        • Sequelize One-to-Many Association example with Node.js & MySQL
    • Node.js with NOSQL databases
      • Node.js + MongoDB: User Authentication & Authorization with JWT
      • Node.js, Express & MongoDb: Build a CRUD Rest Api example
      • MongoDB One-to-One relationship tutorial with Mongoose example
      • MongoDB One-to-Many Relationship tutorial with Mongoose examples
      • MongoDB Many-to-Many Relationship with Mongoose examples
  • Upload files
    • How to upload multiple files in Node.js
    • Upload & resize multiple images in Node.js using Express, Multer, Sharp
    • Upload/store images in MySQL using Node.js, Express & Multer
    • How to upload/store images in MongoDB using Node.js, Express & Multer
  • React Grimoire
    • React Doc
    • React Grimoire
    • React Cheat Sheet
  • spring boot Grimoire
    • Getting started
    • Spring Boot, Spring Data JPA – Rest CRUD API example
    • Spring Boot Token based Authentication with Spring Security & JWT
  • Mongo Grimoire
    • MongoDb-Mongoose Cheat Sheet
  • Development tools
    • Design Patterns
  • maissen_grimoire
Powered by GitBook
On this page
  • MongoDB
  • MongoDB Console
  • Mongoose Installation
  • Mongoose Basic Usage
  • Mongoose Schema
  • Create, Read, Update, Delete (CRUD) Mongoose Example
  • Mongoose Model Methods
  • Mongoose Document Methods
  • Query Helpers
  • Indexes

Was this helpful?

  1. Mongo Grimoire

MongoDb-Mongoose Cheat Sheet

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
PreviousSpring Boot Token based Authentication with Spring Security & JWTNextDesign Patterns

Last updated 1 year ago

Was this helpful?