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.
Mongoose is a JavaScript object-oriented programming library that creates a connection between MongoDB and the Node.js JavaScript runtime environment.
NodeJS
<--> Mongoose
<--> MongoDB
Install Mongoose: npm i 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
database.js
in src folder.database.js
import mongoose from "mongoose"
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 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;