Creating a Model

ninemoonz·2022년 8월 1일


목록 보기

Connecting MongoDB with our server

import mongoose from "mongoose";

mongoose.connect(process.env.DB_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

Model Schema

  1. Have to teach our database how data looks like (Shape)
import mongoose from "mongoose"

const videoSchema = new mongoose.Schema({
  title: String, // Shortcut when you only have one specification.
  description: {type: String, required, ...}, // When you have more then one specification for the data.
  createdAt: Date,
  hashtags: [{type: String,}],
  meta: {
  	views: Number,
    rating: Number,
  1. Create a Model which follows the Schema
const Video = mongoose.model("Video", videoSchema);
//objectName = mongoose.model("nameOfModel", Schema);

export default Video;

Importing db and model to server.js (or init.js)

import "./db";
import "./models/Video";

On a journey to be a front-end developer

0개의 댓글