MongoDB & Mongoose

Jun's Coding Journey·2022년 11월 10일
0

[Challenge] Youtube Clone

목록 보기
9/19

MongoDB

MongoDB is an open source NoSQL database management program. What differentiates MongoDB from other SQL-based databases is the fact that it is object-based. Traditionally, databases were only SQL-based where they work with rows and columns (just like excel). With NoSQL-based databases, we can directly work with objects to store, retrieve, update, and even delete data. As such, MongoDB is useful for working with large sets of ditributed data because it support various forms of data.

MongoDB can be easily downloaded on MacOS. Since the main program of MongoDB is priced, it is recommended to download the free community version instead. By simply inputting the specified command on your terminal, we can install MongoDB on our computer (it can be a little more complicated on windows...).

// required Xcode command-line tools for running MongoDB
xcode-select --install
// homebrew formula for MongoDB
brew tap mongodb/brew
// latest version of MongoDB(version # can change!)
brew install mongodb-community@6.0

Be sure to check that MongoDB is running normally with the mongod and mongo (for Mac users, use mongosh).

Mongoose

Mongoose is an object data modeling (ODM) library for MongoDB and Nodes.js. In simple terms, Mongoose acts as bridge from node.js to MongoDB. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those object in MongoDB.

Mongoose can be easily installed and imported from npm (after creating a new db file, don't forget to import it to the server file!).

// installing mongoose from npm
npm i mongoose
// importing mongoose to a new db file
import mongoose from "mongoose";
// importing db file to server.js
import "./db";

We can check if our database is running by creating functions that detects whether the database is functional or not.

// check if your db is functional
const db = mongoose.connection;
const handleOpen = () => console.log("✅ Connected to DB");
const handleError = (error) => console.log("❌ DB Error", error);
db.on("error", handleError);
db.once("open", handleOpen);
profile
Greatness From Small Beginnings

0개의 댓글