MongoDB and Mongoose

PussinSocks·2022년 7월 21일
0

CloneCoding

목록 보기
12/20

MongoDB

MongoDB is an open source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.

  • Document-based (distinguished from sql-based(row-based) database.
  • Document-based is like treating data as objects. (JSON-like documents)

Mongoose

Mongoose is a JavaScript object-oriented programming library that creates a connection between MongoDB and the Node.js JavaScript runtime environment.

  • It take a role of translating js commands into MongoDB
    NodeJS <--> Mongoose <--> MongoDB

Install Mongoose: npm i mongoose

Mongoose Query Docs->


How to use MongoDB and Mongoose

Terminal:
mongod
=> Open up mongoDB
mongo

but mongo got deprecated recently, so it is recommended to use
mongosh

=> Lets you in the mongo shell

Connecting the server with DB

  1. Make a database.js in src folder.
  2. import mongoose in the database.js
import mongoose from "mongoose"
  1. When you connect to the Mongo Shell, terminal will tell you the URL, and copy the URL and type like this in database.js:
//database.js
mongoose.connect(MongoDB_URL, { useNewUrlParser: true, useUnifiedTopology: true});

const db = mongoose.connection; //Mongoose give access to the connection

const handleOpen = () => console.log("✅ Connected to DB ");
const handleError = (error) => console.log("❌ DB Error", error)

db.once("open", handleOpen) //Only happens once
db.on("error", handleError); //on can happen many times

Schema and Model

Schema is the shape of the model. Here, you can choose the number of objects, name of the objects, data types of objects.

//define the shape: schema
const videoSchema = new mongoose.Schema({
    title: String,
    description: String,
    createdAt: Date,
    hashtags: [{type: String}],
    meta: {
        views: Number,
        rating: Number,
    },
});

Model is the actual data format made with the schema and gets used as an actual database.

//actual model
const Video = mongoose.model("Video", videoSchema);
export default Video;
profile
On a journey to be a front-end developer

0개의 댓글