Basic of MongoDB
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
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 acknowledged, insertedID, or insertedCount
insertOne
InsertMany
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:
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
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
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
Create model and insert data
mongoose will use model names as collection names (Table names)
Model Schema
Model Type Required
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)