Defining Mongoose Schemas and Models

Introduction

In this lesson, we'll dive into the practical aspects of using Mongoose with Express to create and view a todo item via an API. By the end of this lesson, you'll know how to define a Mongoose schema and model, create a sample todo item, and view it.

What You'll Learn

In this lesson you'll learn:

  • How to set up an Express server with Mongoose.
  • How to define a Mongoose schema and model with additional fields.
  • How to create a sample todo item.
  • How to view the created todo items via the API.

Step 1: Importing Libraries and Setting Up Express Server

We'll start by importing the required libraries, initializing our Express application, and setting up middleware to parse JSON request bodies.

const express = require('express');
const mongoose = require('mongoose');

const app = express();

// Middleware to parse JSON request bodies
app.use(express.json());

Here, we:

  1. Import express and mongoose.
  2. Create an Express application instance.
  3. Use middleware to allow our Express application to understand and parse JSON bodies from incoming requests.

Step 2: Connecting to MongoDB

Next, we'll establish a connection to our MongoDB database.

// Set mongoose strictQuery to true to suppress deprecation warning
mongoose.set('strictQuery', true);

mongoose.connect('mongodb://127.0.0.1:27017/todo-app', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})
.then(() => console.log("Connected to MongoDB"))
.catch((error) => console.error("Failed to connect to MongoDB:", error));

This code:

  1. Connects to a MongoDB database named todo-app running locally.
  2. Logs a success message upon successful connection.
  3. Catches and logs any connection errors.

Step 3: Defining Mongoose Schema and Model

Now, let's create a schema and a model for our todo items.

const todoSchema = new mongoose.Schema({
    task: { type: String, required: true },
    status: { type: String, required: true }
});

const Todo = mongoose.model('Todo', todoSchema);

Here we:

  1. Define a schema with two fields: task, which is a required string, and status, which is also a required string.
  2. Create a Todo model from the schema, which we will use to interact with the todos collection in MongoDB.

Understanding Automatically Added Fields: _id and __v:

Mongoose automatically adds some fields to each document, which you may notice in the API responses:

  • _id: Mongoose adds an _id field to each document, which uniquely identifies the document within the collection. This is similar to a primary key in a relational database and is essential for distinguishing individual documents.
  • __v: Mongoose also adds a __v field to track the version of the document. This is useful for handling concurrency and ensuring that updates to documents are applied correctly.

Now, let's move on to creating API routes to handle creating and viewing todo items.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal