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
- key-value: like a dictionary / hash map
- Document: like JSON (MongoDB)
- Column
- 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
- schema: same as a collection
- model: actual constructors used to create objects
- object: same as document
- Mongoose only throws error when there is actually an err, not finding something is not an error https://stackoverflow.com/questions/38329730/mongoose-always-return-null-instead-of-an-error-when-no-result-found
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 ???