All About CRUD - Model / Schema / Query

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

[Challenge] Youtube Clone

목록 보기

CRUD (Create, Read, Update, Delete) is an acronym which refers to the four basic operations a software appliaction should be able to perform - Create, Read, Update, and Delete. When creating an application, users mus be able to create data, have access to the data in the UI by reading the data, update or edit the data, and delete the data. If we think about all the webpages and apps we use everyday, we are able to do all of these things.

If we go even deeper, a full-fledged application will also be able to use and API(or server), a database, and a user interface(UI). More of this will be discussed in another time.


A model is a data structure that we use to describe how our data looks like. It is part of a software that holds the data that is to be manipulated by the controller, and displayed by the view. Without the use of models, we would have to manually create all the objects and describe them one by one. With the help of models, we can filter and manage any number of data that passes through an application with ease.


Before trying to create a model, we first need to define the shape of the model we are trying to create. We can do this with a framework called schema. This difference can be confusing, but all we are doing is describing how the model will look like and not putting any data yet.

const exampleSchema = new mongoose.Schema({
  title: String,
  description: String,
  createdAt: Date,
  hashtags: [{ type: String }],
  meta: {
    views: Number,
    rating: Number,

Now that we have a schema, we can create a model. We simply need to take the name of the model and the schema inside a new variable. Then, we can finally export the model to the server. For organizing purposes, we can create a separate init file to import all the files related to models. In this case, make sure the change the name of the initializing code on package.json.

import "./models/Model";

Creating a Query

To start using a model, we first need to import our model at a controller file. Now that we connected our model, we can freely use all the mongoose methods and render them on the controllers.

For example, the model.find() method is able to search for a data within a database. After searching, the model will return the results through specified callbacks. After the callback is initiated, the controller will render the result onto the browser.

export const home = (req, res) => {
  Video.find({}, (error, videos) => {
    return res.render("home", { pageTitle: "Home", videos });
Greatness From Small Beginnings

0개의 댓글