Prevent redundant entries in MongoDB with Mongoose to optimize database efficiency

Hi there, I'm currently exploring MongoDB and Mongoose. My goal is to prevent users of my API from storing duplicate contact names in the Mongo database, but unfortunately it's not working as expected.

This is how I have set up the validation: both name and phone number are required fields, with the added condition that the name must be unique; otherwise an error should be thrown.

const contactSchema = new mongoose.Schema({
        name: {
            type: String,
            required: true,
            unique: true
        },
        number: {
            type: Number,
            required: true
        }
    });

app.post('/api/persons', (request, response) => {

    const body = request.body;

    const person = new Contact({
        name: body.name,
        number: +body.number
    });

    person.save()
        .then(saved => {
            response.json(saved);
        })
        .catch(error => {
            return response.status(400).json({
                error: 'content missing'
            });
        });

})

While sending a post request with missing name or number does trigger an error, the unique value validation doesn't seem to be functioning properly.

Answer №1

Dealing with unique validation errors can be a bit tricky. To make it easier, you can utilize the unique-validator plugin. Once implemented, if you attempt to send a post request without providing a name or number, you will receive an error message stating that these fields are required: true

If you want more information on how validation works in Mongoose, check out validation

It's important to note that validators do not run on values that are undefined, with the exception of the required validator.

Answer №2

It is essential that both the fields (name and number) in your database are mandatory.

To ensure data integrity, it is recommended to handle the request body before querying the database. Consider this approach:

const name = body.name;
const number = body.number;

if (!name || !number) {
     //  Send a response indicating that one of the fields is empty.
}

let personDetails = {
     "name": name,
     "contact": contact
};

const person = new Contact(personDetails);

For unique validation, you can either utilize the unique-validator plugin suggested by Mohammad Yaser Ahmadi or perform a database query to verify the uniqueness of name and number before saving if suitable for your DB system.

If you require both name and number to be collectively unique, you can establish a Compound Index like this:

contactSchema.index({ name: 1, number: 1 }, { unique: true });

For more information on Compound Indexes, refer to: https://docs.mongodb.com/manual/core/index-compound/

Answer №3

After much searching, I finally stumbled upon a package that helped me avoid duplicate entries in my Mongo database. I followed the instructions provided in the documentation of this amazing package:

https://github.com/blakehaswell/mongoose-unique-validator#readme

This is the code snippet that did the trick for me:

const uniqueValidator = require('mongoose-unique-validator');

const contactSchema = new mongoose.Schema({
        name: {
            type: String,
            required: true,
            unique: true
        },
        number: {
            type: Number,
            required: true
        }
    });

    contactSchema.plugin(uniqueValidator);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Injecting input values into a mongoose query within the initial parameter

Utilizing the MEAN stack, there exists a specific entry in my MongoDB database as seen below: { "_id" : ObjectId("5577467683f4716018db19ed"), "requestMatrix" : { "1698005072" : { "rideId" : "641719948", "status" :"accepted" },"1698005073" : { "rideId" : " ...

issue encountered while attempting to install oracledb using npm

When attempting to install node oracledb on Windows 7, I encountered an error message. Here is a screenshot of the error: npm install oracledb I diligently followed all the steps outlined in this tutorial Installing node-oracledb on Microsoft Windows, but ...

Tips for removing the embed from specific messages and messages originating from specific users or bots with Discord.js

I'm currently working on developing a bot with the ability to selectively remove embeds from certain messages or links shared by specific users and bots within the server. For instance, if someone posts a tweet and I don't want to see the Twitte ...

Express API on Node.js fails to read Post request JSON data as null

Currently, I am in the process of developing an application utilizing the Mern stack. One of the recent tasks I have accomplished is sending a POST request from the React frontend to the endpoint using Axios. The snippet provided below showcases the code f ...

Fixing problems encountered when asynchronously gunzipping an already read file in Node.js

As a newcomer to the world of node.js and asynchronous programming, I have successfully used promises to read files with fs readFile, but I am struggling with getting zlib Gunzip to function as expected in my Coffeescript code: promisifyRun(fs, 'r ...

What is the best way to transfer a request parameter from a URL to a function that generates an object with matching name in JavaScript?

I need to figure out how to pass a request parameter from an express router request to a function that should return an object with the same name. The issue I'm facing is that the function is returning the parameter name instead of the object. Upon c ...

Standardizing URLs with ExpressJS router

Seeking normalized/canonical URLs for a single page application running on an ExpressJS server. While the SPA is supported by a server-side router, templates can vary slightly for different app URLs. One particular difference is the presence of the <li ...

What is the purpose of requiring the explicit invocation of app.listen(port) to enable express-ws to function properly?

I've recently started exploring NodeJS Express and came across the official tutorial from express-ws for setting up websockets in a simple project generated using npx express-generator. While following the tutorial, I noticed that in the app.js file, ...

Exploring the world of routing parameters in Express.js and AngularJS

Struggling to configure routes with parameters in an AngularJS application supported by a node.js server running on express. The setup involves Node routing all unspecified paths to a catch-all function: app.use(express.bodyParser()); app.use(app.router); ...

The npm -g list command is not showing any results, however, running npm list will display the

Having encountered a strange issue, I have been unable to locate a similar problem on Stack Overflow (which is quite unusual) so I decided to ask here. The npm -g list command does not display anything for me. Not even when using the --empty option. It ju ...

Could anyone lend a hand in ensuring that my AJAX call successfully processes the parameters?

When attempting to retrieve specific data from my database using AJAX, I encountered an issue where the call was successful when made through Postman or directly in the browser, but failed when initiated from my client. It seemed to work intermittently, re ...

Encountering issue: LineChart is not recognized as a constructor, resulting in failure to display chart on webpage

I am struggling with displaying a chart in my HTML file that should show the details of a specific process from the past few minutes. Whenever I try to initialize the chart using google.charts.load('current', {'packages':['line&apo ...

I am unable to locate the module 'fs': I have exhausted all possible solutions to fix this problem

Attempting to delete a file from the local system using the unlink function, but encountering an error stating that it cannot find the module 'fs'. Below are some details on the relevant files: app.component.ts import * as fs from 'fs&apos ...

The Sequelize many-to-many relationship fails to display the outcome when making a GET request

Recently, I've started working with relational databases. The backend of my project is built using Node.js and Express, with a REST API and Postgresql as the database. For connecting to the database and defining models, I am using Sequelize. So far, I ...

There are no Vue.js updates reflected in Heroku when using Laravel

I've encountered an issue with Heroku (PaaS). I'm in the process of launching my first project using Laravel, and I'm consistently making changes. It's my understanding that every modification made during development needs to be pushed ...

moving passport objects between different routes

Feeling a bit lost in setting up my node application with Express and Passport for authentication. Came across a helpful guide by scott.io that got me started here Everything works fine, but I want to organize my routes better. Planning to have separate r ...

Looking for a more efficient approach for my CircleCI testing process

My current CircleCI yaml file runs a separate test script for each app, which is not "DRY." I believe a better solution would be to run the test script from the root directory and loop over each app. However, I'm having trouble figuring out how to do ...

The function res.write() is used to send data that has been joined

I am currently utilizing an express node server and looking to receive response data in chunks at the client. However, I am encountering a problem where the data is being concatenated. For instance, on the server side, I have a loop that looks like this: ...

Make sure to refresh the node.js express api every minute with the latest timestamp available

I'm currently working on setting up a Node.js Express API to expose a MySQL table. Everything is working fine except for the part where I need to filter data by a current timestamp and update it every few minutes. I've tried using setInterval but ...

Dealing with the mystery of the Next.js Stripe webhook elusive function error

I've been working on setting up a Stripe webhook in my NextJS app to write data to Firebase Firestore, but for some reason, stripe.webhook.constructEvent is showing up as undefined even though everything seems to be properly configured. I'm usin ...