CS9 Mongo Day 1

2018-06-07

Mongod:

mongod is a database server

Database

A databases is a collection of data organized in a way that is easy to get information

Query

A query is asking questions about data or executing comamnds to operate on the stored data

DBMS (Database Management System):

Software that provides a way to store/retrieve data In charge of creating databases (can have more than one database in it) Normally run as a server Handles memory, security, etc.

In any software you build, there are multiple moving parts.

Client (front-end) <-> API (back-end) <-> DB server (for persistent data storage)

NoSQL (Not Only SQL): a type of database

  • key-value pairs
  • graph databases (tree-like structures)
  • document <- MongoDB is one of the vendors

Document databases store information as a document.

Mongo Server

  • Databases (example, Lambda)
  • Collections (the group of users)
  • Documents (individual users) ({_id: dfafddafdafd, username: user5}) -Fields (_id, username)

Data modeling:

How data is going to be stored

  • Abstract only information you need to make the system work Example:
  • Mechanic needs specific parts of an automobile, but a dealer would need color, make, model, etc.
  • Both still need information for a vehicle
  • It's important to know what's needed by the user

MongoDB:

Pros:

  • popular (has a lot of support)
  • mature (over 10 years old, has a lot of bugs worked out)
  • JavaScript from beginning to end (no context-switching)
  • Dynamic schemas (shape of data: properties and data types)

Cons:

  • Dynamic schemas
  • if you change the name of a field in the database, you have to deal with both naming schamas, which can be difficult
  • No joins

Student question: Is Mongo safer to store data? SQL: Structured Query Language

SQL-injection: Vulnerability to the access of data Some systems that access SQL use strings and are vulnerable to attacks

Answer:

  • SQL-injection vulnerability is an application design flaw, not a SQL design flaw.

DBAAS (Database as a Service):

  • MongoDB

  • mLab (used to be Mongo Lab) Advantage:

  • Don't download local instance, you connect to their service and they store your data. Offers 500mb tier for free

    127.0.0.1 - IP address to local host

If there are no documents in a database, the database does not show up in show dbs

  • Unless it's one of the defaults (admin, local, config)

REPL - read evaluate print loop

Response you get from insert (nInserted) is the number of things inserted

Every document inserted into a collection wil be given an ID unless one is provided.

  • You generally don't want to provide an ID because the ones that are generated by the system are unique
  • They use a safe algorithm to generate unique ID

Client <-JSON-> [API (driver)] <-BSON-> [DB-Server] The driver translates the language of the client to something the database understands

Mongoose

  • Wraps native MongoDB driver
  • You can still use MongoDB driver, but it is more verbose
  • Schemas (can set rules that will help Mongoose validate before things are added to the database).
  • Middleware with Mongoose can extend functionality (4 types) validation
  • models

Workflow

  • connect API to Mongo
  • define schema
  • compile schema into a model
  • A mongoose model
  • Create a mongoose document by instantiating (calling new) on a model
  • use mongoose document to interact with the database document

mongoose.connect(URL)

  • Previously we've used HTTP protocol for connections
  • HTTP protocols are stateless
  • MongoDB uses their own stateful protocol:
  • ('mongodb://server:port/databaseName')
  • example: mongoose.connect('mongodb://localhost/beardb')

If yarn start does not work, try deleting Yarn Lock, yarn, yarn start

Reason you create schema: compile into model { species: String } <- shorthand syntax (when only one property)

species: {
    type: String,
    required: true
}

^ longer form

Schemas

const schemaName = mongoose.Schema(definition, options) Definition example:

const definition = {
    type: String,
    required: true,
    unique: true,
    },
    latinName: {
        type: String,
        require: true
    },
    createdOn: {
        type: Date,
        default: Date.now()
    }
});

Options example:

const options = { timestamps: true } - this will create createdAt and modifiedOn fields in addition to fields specified in the schema

const schemaName = new mongoose.Schema(definition, options)
const \_\_\_\_model = mongoose.model('ModelName', schemaName, 'collectionName')

By default, mongoose will take the name of the model, lowercase it, pluralize it, and that will be the name of the collection in the database. If you have an existing collection name that might conflict, you might want to set the third argument to a specific collection name.

Optional Syntax for Routing:

router.route('/').get(get).post(post)

function get (req, res) {
    res.status(200).json({ route: '/api/bears' })
}

function post (req, res) {
    const bearDate = req.body
    const bear = new Bear(bearData)
    bear
        .save()
        .then(bear => {
            res.status(201).json(bear)
        })
        .catch(err => {
            res.status(500).json(err)
        })
}