Validating Data and Handling Duplicate Entries in MongoDB Using Mongoose

Validating Data and Handling Duplicate Entries

In today’s lesson, we will learn how to ensure the data we work with is correct and how to avoid having the same data more than once in our MongoDB database using Mongoose. This is crucial because making sure our data is accurate and unique helps our applications run smoothly without errors or confusion.

What You'll Learn

In this lesson, you'll learn:

  • How to validate data in Mongoose schemas.
  • How to handle and prevent duplicate entries.
  • Practical examples to implement these concepts in a simple web application.

Step 1: Setting Up the Express.js Server and Connecting to MongoDB

Let's start by setting up an Express.js server and connecting it to our MongoDB instance. This allows us to serve our application and communicate with the database.

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

const app = express();
const PORT = 3000;

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

// Connect to MongoDB
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));

app.use(express.json());

In this part of the code, we set up an Express.js server and connect to a MongoDB database named todo-app running on localhost. The useNewUrlParser and useUnifiedTopology options are included to avoid deprecation warnings. We also use the express.json() middleware to parse incoming JSON requests, which is essential for handling JSON payloads in API requests.

Step 2: Defining Mongoose Schemas

Next, let's define schemas for our data models. Schemas in Mongoose act like blueprints for the documents in your collections. This is important because it allows us to enforce a structure on our data and add validation rules.

// Define schema for categories
const categorySchema = new mongoose.Schema({
    name: { type: String, required: true }
});

// Define schema for ToDo items with a reference to categories
const todoSchema = new mongoose.Schema({
    task: { type: String, required: true },
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' }
});

In this part of the code, we define two schemas using Mongoose: one for categories and one for ToDo items. The categorySchema has a single field name which is required. The todoSchema has a task field which is a string and is required, and a category field which is a reference to a Category document. These schemas help ensure that every document in the respective collections follows a defined structure and validation rules.

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