- Build a RESTful API using Express and Node.js.
- Persist API Data to a Database. (this week)
- Secure an API.
- Unit Testing.
- Backend Project Week.
- verify mongo installation.
- verify mongo is running (don't stop it until you're done working with it).
- quick intro to databases.
- what is NoSQL and what are document databases.
- why MongoDB.
- working with local instance of MongoDB. DBAAS options.
- a BRIEF look at the mongo shell.
- connecting to MongoDB from our API.
- mongoose
- what is it?
- benefits and drawbacks.
- mongoose Schemas ad Models.
- define a basic document Schema and Model.
- creating database documents.
- querying all documents.
- querying one document by id.
Collection of data, organized, easy to get information out of it.
Asking questions about our data or executing commands to operate on the stored data.
Software that provides a way to store/retrieve data.
Client <-> [ API <-> DB Server ]
NoSQL (Not Only SQL): a type of database
- key-value pair
- graph
- document <- MongoDB
const user = {
username: 'admin',
password: 'secret',
};
MongoDB Server
- databases (lambda)
- collections (users, roles, products)
- documents ({
_id
: 'qeworjoasjf;lkjeorir0', username: 'admin' })- fields:
_id
, username
- fields:
- documents ({
- collections (users, roles, products)
Why MongoDB
- popular
- mature
- JS end to end
- dynamic schemas (shape of the data [properties and data types])
cons
- dynamic schemas
- no joins
DBAAS (database as a service)
- offer free 500mb tiers
- MongoDB Atlas
- mlab
Client < JSON > [ API (driver) ] < BSON > [ DB Server ]
Mongoose
- wraps the native mongodb driver
- schemas and models
- middleware
- validation
- query builder
- ...
Workflow
- connect your API to mongo
- define a schema
- compile the schema into a model
- create a mongoose document by instatiating (calling new on) a model
- use the mongoose document to interact with the db document
- what is mongoose?
- what is a mongoose schema?
- is mongoose a good fit for data that is dynamic (very little to no structure)?
- if my database server address is:
dbonline.com
and my database name iszoodb
, build a connection string using the default port (27017).- mongoose.connect('mongodb://dbonline.com/zoodb')
- a MongoDB server can have many databases?
- a JS object is stored inside MongoDB as a document?
- a mongoose Schema compiles into a mongoose model?
- a group of related documents is stored inside a collection?
- quick tour of MongoDB Compass
- finish CRUD endpoints
- a look at supported data types
- importing data
- modeling relations
- one to one
- one to many
- many to many
- embedded documents/schemas, AKA sub-documents
- linking or refs
- data population
- querying data
- sorting
- projection
- filtering
One to One: start with embedding (sub-documents)
- One user has one profile.
- One patient has one medical record.
- One person has one Spouse.
One to many: start with a ref (linking)
- most common type of relation
- one order has many order lines.
- one city has many citizens.
One to few: could be embedded or linked (ref).
- a book can have more than one author.
- an author can have many books.
- a blog post have a few comments.
Many to Many(few)
- books and authors
- users and roles
- departments and employees : one to many
Querying Data
let query = Character.find();
Character.find().sort('name') // by name ascending Character.find().sort('-name') // by name descending Character.find().sort('gender -height') // multiple fields Character.find().sort({ gender: 1, height: -1}) // multiple fields
Character.find().select('name gender') Character.find().select({name: 1, gender: 1}) Character.find().select({name: 1, gender: 1, _id: 0}) // excludes _id (it is always returned by default)
Character.find({ gender: 'female'}).sort('height').select('name').then().catch();
const gender = req.query.gender;
let query = Characters.find();
if (gender) {
query.where({ gender: gender });
}
query.then(chars => res.json(chars)).catch();
query.where('age').gte(18).lte(62);