Appendix D. MongoDB and Mongoose cheatsheet

 

When you develop your own projects, searching on the internet for React documentation and APIs or going back to this book’s chapters to find a single method isn’t efficient. If you’d like to save time and avoid the distractions lurking everywhere on the Net, use this MongoDB cheatsheet as a quick reference.

Print-ready PDF available

In addition to the text version presented here, I’ve created a free beautifully designed, print-ready PDF version of this cheatsheet. You can request this PDF at http://reactquickly.co/resources.

MongoDB

  • $ mongod—Starts the MongoDB server (localhost:27017)
  • $ mongo (connects to the local server by default)—Opens the MongoDB console

MongoDB console

Installing Mongoose

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

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

Mongoose document methods

sitemap