CodeBlanks Logo Icon CodeBlanks

Model

Learn CRUD operations with Mongoose Model.

What is a Model?

A Model is a document class built from a blueprint. You do database operations (create, find, update, delete) through this class. The Model is Mongoose's most-used API.

Creating a model: const User = mongoose.model("User", blueprint). The first parameter is the collection name (pluralized), the second is the blueprint. After creating you make documents with new User({...}) and query with User.find().

Creating a model

To create a model you call mongoose.model(name, definition). name sets the collection name (Mongoose auto-pluralizes: "User" becomes "users"). definition is the blueprint object.

You define a model once; then you use it everywhere in the app. Defining the same name twice throws an error. The model lives in memory; you do not need to require it again. This is Mongoose's singleton pattern.

Practice Log the type of the model

Import mongoose. Create a model with mongoose.model("User", { name: String }). Log typeof User.

Starter code

index.js
// import the module

// create a model

// log its type

Sample solution

index.js
const mongoose = require("mongoose");
const User = mongoose.model("User", { name: String });
console.log(typeof User);

Expected output

function

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
mongoose.model Creates a model
Model Document class
new Model() New document
Model.find() Finds documents

2 Complete the method name

Question
const User = mongoose.____("User", { ad: String })
Answer
const User = mongoose.model("User", { ad: String })

Explanation: mongoose.model("User", ...) returns a Model class.

3 What does mongoose.model() return?

  • Bir dize
  • A number
  • A Model class Correct answer
  • Bir Promise

Explanation: mongoose.model() returns a Model class.

All lessons in Advanced