Databases, MongoDB, and Mongoose - ryantc94/Knights-of-Arthur GitHub Wiki

Relational Databases

  • Tables
  • Each Table has columns and the rows contain data
  • each row/column block contains a primary key to id it
  • Follows ACID
  • http://r937.com/relational.html
  • Examples: MySQL, PostgreSQL, Oracle, Microsoft SQL Server

NoSQL

  • Types
  1. key-value: like a dictionary / hash map
  2. Document: like JSON (MongoDB)
  3. Column
  4. Graph … https://en.wikipedia.org/wiki/NoSQL#Types_and_examples_of_NoSQL_databases

MongoDB

  • Document is a single record in MongoDB
  • Collection is a group of documents

Commandline

  • mongod: to start mongodb
  • mongo: to connect client to local instance

Shell Commands

  • show databases

  • use [database] <- adds a database

  • show collections

  • db.dropDatabase()

  • db.collectionName.drop()

  • help

  • CRUD (create, read, update, delete)

  • db.[collection].insert(obj)

  • db.[collection].find(obj)

  • db.[collection].update(obj, obj)

  • db.[collection].remove(obj)

Mongoose

ORM/ODM (how do these work???)

  • map objects in your app to their counterparts in your database

Steps:

Create file called db.js

const mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost/catdb);

//Create Schema

const Test = new mongoose.Test({
name: String,   <- Datatype
updated_at: Date
});

//register Schema

mongoose.model(‘Test’, Test)

App.js 

// initializes connection to db
require(./db)

Routes

const mongoose = require(‘mongoose’)
const Test = mongoose.model(‘Test’)

.post(url, function(req, res) {
new Test({
name
update
}).save(function(err, test, count) {
res.redirect
})
})

Embedding Documents

Foo: [Bar] <- Foo contains array of Bar

Field Specifications

type max min
required default

Slugs ???