Skip to content
youhoc
  • Pages
    • Home
    • Modern App Guidelines
    • Linux
      • Day 1: Linux Distributions & Navigation
      • Day 2: User Management
      • Day 3: File Permission & Ownership
      • Day 4: Package Management
      • Day 5: Services Management
    • Javascript
      • JS The Weird Part
        • Execution Context
        • Types & Operators
        • Objects & Functions
        • Error Handling & Strict Mode
        • Typescript, ES6, Tra
      • Modern JS
        • JS in the Browser
        • Data Storage JSON
        • Modern JS
        • Advanced Objects & Methods
        • Webpack & Babel
        • Async
      • jQuery
        • In-depth Analysis of jQuery
      • React-ready JS
        • Arrow Function
        • Template Literals
        • Logical AND, OR, Ternary, Nullish Operators
        • Destructuring & Rest Operator
        • Array Method
        • Immutability and Spread Operator
        • Promises, Async/Await, Callback
    • PHP
      • gruntJS
      • composer
      • MySQL
    • Docker
      • Container Basics
      • Container Networking
      • Container Image
      • Container Volume & Persistent Data
      • Dockerfile
      • Docker Compose
      • Docker Registry
    • Node.js
      • 1. Installing & Exploring
      • 2. Core Modules
      • 3. Get User Input
      • File System & Input Arguments
      • 5. Express Web Server
      • 6. Deploy to Heroku & Github
      • Authentication
      • icon picker
        7. Databases
      • 8. Rest API
    • ReactJS
      • React from Andrew
        • Summary from Next
        • 1. Basics
        • 2. React Components
        • 3. Webpack
        • 4. Styling with SCSS
        • 5. React Router
        • 6. React Hook
      • Modern React From The Beginning
        • Intro to JSX
        • Vite Build Tools
        • Basic Component Creation
        • Component State
        • Props & Component Composition
        • useState with Inputs & Form Submission
        • useEffect, useRef & Local Storage
        • Async / Await and Http Request in React
        • React Router: Declarative Mode
        • ContextAPI
        • React Router: Framework Mode
          • File-routing & HTML Layouts
          • Server-side Data Query
          • Links & Navigation
          • Loaders
    • Typescript
      • Type User vs UserProp
    • Payload CMS

7. Databases

Basic of MongoDB

Screen Shot 2022-03-03 at 8.29.32 PM.png

Install MongoDB
Download Community Version
Move installer to a permanent folder
Create a mongodb-data folder
run command to map data folder
Install Mongo DB GUI
Robo 3T

Install MongoDB Driver
API
npm package
Initiate the DB
Select / Create a database name
if a database does not exist, Mongo will create one
dat sai ten tu tao ra 1 DB moi

INSERT a Document (Row)

Return result or error after insert a document
use ops (version 3.3)
use acknowledged, insertedID, or insertedCount

insertOne
acknowledged
insertedId

InsertMany
acknowledged
insertedCount
insertedIds

InsertMany

The objectId

return by result properties “insertedIds”
objectId is unique across collections (Tables)
unlike MySQL which unique ID is an interger (and can be duplicate accross tables)
objectId consist of:
4-byte timestamp
5-byte random value
3-byte counter from random value
You can get timestamp of a document by
no need to store date added?
You can provide your own objectId by setting _id value
but no need to do that
You can get the ID inside objectId by using:

READ document in MongoDB

User Collection / find or findOne
findOne returns the first one if found many
findOne by exact unique ID
findOne return the whole object

find only return cursor
version 4.4: findCursor
find does not have a callback function
must use with one of these constructor: limit, count, toArray, forEach

UPDATE a document / row

If no callback passed, promise will be used
User $set or $unset constructor
$inc - incremental

DELETE a document / row

deleteOne
deleteMany
MySQL npm driver
MongooseJS
Data Validation and Modelling for MongoDB
Install
Connect to DB and insert a document
just like MongoDB
Create model and insert data
mongoose will use model names as collection names (Table names)

Model Schema
Booleen
String
trim: true / false
lowercase: true / false
Number
Model Type Required
required
validate
default

Data Validation & Sanitization

Validation = check if value is required and right format
use built-in Mongoose Validation
or install validator npm package
Sanitization = process value to have right format

Collection Relationship

Users DB stores all Tasks ID
OR
Task DB store User ID (better approach)
Reference to OwnerID in Collection you store Tasks
owner: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
}
The popular Task Owner ID into User Object
// get task ID (without owner ID)
const task = await Task.findById(_id)

// accessing task owner ID
// console.log(task.owner)

// but what if we need to get owner name???
// leverage ref property in User model
// populate the owner ID to owner object
await task.populate('owner').execPopulate()

// task owner is now an object, not just ID
console.log(task.owner)
Virtual Field to Tasks in Collection you store User
// setup a virtual property to store task by a user
userSchema.virtual('userTasks', {
ref: 'Task', // this virtual fields under User link to Task model
localField: '_id', // link from this User model
foreignField: 'owner' // link to destination Task model
})
Then access a User task by
// get current user
const user = User.findById(_id)

// this will return null because we don't have link
// console.log(user.tasks)

// we need to create virtual fields
// then populate just like task
await task.populate('userTasks').execPopulate()

// this will return all tasks object by this user
console.log(user.tasks)
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.