When the register button is clicked on the registration page, duplicate emails are being stored in MongoDB

Whenever I try to register with the same email on the registration page, it still gets recorded in my MongoDB database when I don't expect it to be saved.

I attempted to set 'unique: true' for the email variable in User.js like this:

import bcrypt from 'bcrypt';
import { Schema, model, models } from "mongoose";



const UserSchema = new Schema({
    email: {type: String, required: true, unique: true},
    password: {
        type: String, 
        required: true, 
        validate: pass => {
        if(!pass?.length || pass.length < 5){
            new Error('Password must be at least 5 characters long');
            return false;
            }
        },
    },
    
},{timestamps: true});


UserSchema.post('validate', function (user){
    const notHashedPassword = user.password;
    const salt = bcrypt.genSaltSync(10);
    user.password = bcrypt.hashSync(notHashedPassword, salt);
})




Answer №1

To establish a unique index in my database, I used the following command:

db.users.createIndex({ email: 1 }, { unique: true })

This action allows mongoDB to maintain the uniqueness of the email field moving forward. It guarantees that no duplicated emails can be added to the collection.

Answer №2

Consider modifying the constant to

const UserSchema = mongoose.Schema
as a possible solution.

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

Issue with NPM package installation due to hostname/IP address not matching certificate's altnames

Need help with npm package installation issue I encountered a problem with NPM while trying to install a package. The error message reads: "NPM is not installing the package. The hostname/IP address doesn't match the certificate's altnames:" H ...

Which is the better choice: utilizing object literals or constructor functions?

I'm feeling a bit puzzled about the best way to create an object in JavaScript. It appears that there are at least two methods: one involves using object literal notation, while the other utilizes constructor functions. Is there a specific advantage o ...

The error message "Access-Control-Allow-Origin header is missing on the requested resource" is still appearing despite having the correct CORS middleware set up

I am encountering the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource" despite having implemented the necessary middleware in my express server. Here is the code snippet of the middleware placed before ...

Parsing error occurred: Unexpected empty character found while attempting to load .lottie files

I have a NextJS application and I'm integrating the dotLottie player from this repository. Even though I've followed the setup instructions provided in the documentation, I keep encountering an error when the component attempts to load the dotLot ...

Using EffectComposer in conjunction with the alpha channel in three.js

Here's the code I'm working with: renderTargetParametersRGBA = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat,stencilBuffer: true }; colorTarget = new THREE.WebGLRenderTarget( SCALE * SCREEN_WIDTH, ...

How to access iFrame in ReactJS using document.getElementById

I am facing a challenge on my website where I need to transfer data (using postMessage) to an iframe. Typically in plain JavaScript, I would use techniques like document.getElementById or $("#iframe") in jQuery to target the iframe. However, I am unsure ...

Is it possible to change the hover highlight rotation on a link without affecting the surrounding elements?

Is it possible to rotate the highlight on a link when hovered? I'm new at this, so apologies if this question seems basic. This is how my css/html is currently structured: .links { display: block; } .links a { color: #000000; text-decoratio ...

Error encountered when auto-generating IDs in Next.js with Firebase Firestore database

Hello, I am trying to access the details of my page in Next.js and retrieve data from a Firestore database. Here is the error message I am encountering: Firebase initialized successfully page.js:32 router.query: undefined page.js:34 Movie ID: undefined p ...

Using a function from one class within another class by passing it as a prop

Below are the methods found in my Search.tsx class. renderSuggestion(suggestion) { <div className="buttons"> <button className="button">View Location</button> <button className="button whitebutton" onClick={this.h ...

Tips for altering the checked status of a radio input in a React component

I'm working with input type radio buttons const AnswerOptions = (props) => ( <> <input type="radio" id="something" ...

Changing Array Object into a different Array Object (with Angular)

I am dealing with an array Object [ { product: "Product A", inStock: 3, onHold: 1, soldOut: 2 }, { product: "Product B", inStock: 2, onHold: 0, soldOut: 1 }] I am struggling to convert it into the new array format below. Any assista ...

Optimal method for establishing a variable when utilizing the @Input decorator in Angular

Imagine we have a Definition called User: export interface User { username: string; email: string; password: string; } Now, in a higher-level component, we aim to send an instance of User to a child component: <child-element [user]="in ...

Authentication using SPA RSA 2048 encryption technology

For my current project involving Angular SPA development, the customer has requested the use of RSA 2048 for authentication. I'm uncertain about how the authentication token will be generated. My understanding is that the token should be created on th ...

What is the best way to implement client side validation for a related input field using JavaScript in a Rails application?

Struggling to find a solution for adding a validation check for a dropdown list that is dependent on another input selection in a different form. It seems like database validation may be necessary, but I'm unsure of the best approach. Any suggestions ...

Breaking down a string using JavaScript

Is there a way to shorten the following code? It currently works for me, but it seems quite long-winded. var str = "some title of an event here, weekday 17:00&nbsp;&ndash;&nbsp;18:00 o’clock, with name of a person"; var date = str.split(&apo ...

Is there a substitute for useState in a Next.js server component?

With my static site at , the only interactive feature being the dark mode toggle, I understand that using useState is not feasible in a server component. export default function RootLayout({ children }: { children: React.ReactNode }) { const [darkMode, ...

When generating a fresh event and attempting to link the event ID to its creator, unexpected obstacles emerged

I am currently working on an application that revolves around events. One of the key features requires users to be logged in to create events, and upon creation, I need to update the user's events array with the event ID. However, I have encountered a ...

The function WebForm_DoCallback is not recognized

Encountering an error where WebForm_DoCallback is undefined. UPDATE WebForm_DoCallback("AccountPageControl1", "FileSave~" + fileName, CVFileSavedServerResponse, null, null, true); function CVFileSavedServerResponse(param, context) { } Why isn't ...

What methods can I use to prompt my JavaScript code to generate a third response?

Currently studying JavaScript and I came up with a basic script to inquire about the number of hours you've put in at work. Following that, it will indicate whether you've reached the required threshold, along with displaying the previously enter ...

Tips for displaying specific HTML elements in AngularJS using ng-repeat and ng-if

I am working with some bootstrap HTML code that includes an ng-repeat function. <div class="row"> <div class="col-lg-4" ng-repeat="p in persons"> <img class="img-circle" src="images/{{ p.image }}" width="140" height="140"> < ...