Mongo automatically generates an index with a null key/value pair

After successfully creating a new user using mongoose at a certain route, I noticed that the validation appears in the console and the user is stored in the mongo database. However, when attempting to create a second user with a different username, an error occurred:

(node:16480) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: .users index: userName_1 dup key: { userName: null }

  1. Why does the index userName_1 exist?
  2. What is the origin of the key userName?
  3. Why is it showing the value as null?
  4. Is there a way to resolve this issue?
router.post('/register', (req, res) => {
    User.findOne({username: req.body.username}, async (err, user) => {
        if (err) throw err
        if (user) res.json('User already exists')
        if (!user) {
            const hashPassword = await bcrtypt.hash(req.body.password, 10)
            const newUser = new User({
                username: req.body.username,
                password: hashPassword,
            })
            await newUser.save()
            res.json('User created!')
            console.log(newUser)
        }
    })
})

This represents the Schema structure:

const userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true,
        lowercase: true,
    },
    password: {
        type: String,
        required: true,
    }
}, {
    timestamps: true,
})

Answer №1

Based on the schema you provided:

username: {
    type: String,
    required: true,
    unique: true,
    lowercase: true
}
    

When using Mongoose, an index will automatically be created to enforce the uniqueness of the username field. This optimization speeds up the process as there is no need for a lookup before insertion.

It's crucial to verify that the username field is being saved correctly in the database as expected. The required: true should handle this, but if you encounter an error indicating a null username, something might be amiss.

Additionally, the use of lowercase could pose challenges when checking for existing users with the findOne method. For instance, creating a user "adam" then attempting to create another user "Adam" could lead to errors. This is because the initial search for "Adam" may return nothing, but when saving the value it gets converted to "adam", causing the uniqueness constraint to fail.

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

How can I utilize the pick parameter in nuxtjs3 useFetch for selecting arrays or performing a deep pick?

Currently working on my nuxtjs3 project, where I am extracting data from an API. Specifically using jsonPlaceholder for this task. Extracting data from a single object is not a problem: const { data: useFetchOnly } = await useFetch('https://jsonplace ...

Issue with nodejs routing: res.redirect causing a 404 error instead of proper redirection

Recently, I started working on a web application using nodejs, express, and mongodb as a beginner. Below is a snippet of my app.js file: var express = require('express'); var path = require('path'); var favicon = require('serve-fa ...

The CORS policy has prevented access to 'https://localhost:7144/api/employees' from 'http://localhost:3000'

I encountered an error while attempting to retrieve data from a web API to exhibit in a React JS application. The console displayed this image of the error Below is a snippet from my program.cs file: (Code snippet from program.cs goes here) Additionally ...

Changing HTML dynamically does not trigger the ng-click event within ng-bind-html

I have developed a custom directive that can display messages along with rendering HTML content that may contain Angular attributes like buttons, anchor tags with ng-click attribute, and more. index.html: <ir-error-panel status="status"></ir-err ...

The function getComputedStyle('background-color') will return a transparent value that does not inherit from any ancestor element

When using getComputedStyle, it is expected to return the final computed CSS property value. However, for background-color, browsers tend to return "transparent" (or rgba(x,x,x,0)) instead of computing the inherited value from ancestors. The method only s ...

Issue arose following implementation of the function that waits for the event to conclude

I've encountered a problem with my HTML and jQuery Ajax code. Here's what I have: <form> <input name="name_field" type="text"> <button type="submit">Save</button> </form> $(document).on("submit", "form", fu ...

Retrieving random data using regular expressions and wildcards

Upon analyzing this specific data structure { _id: ..., data: [ {key: 'articles.0.photos.0.category', value: '...'}, {key: 'articles.0.photos.1.category', value: '...'}, ... ] } ...

Leverage the power of Laravel and ReactJS to beautifully display images

Currently, I am working on a project where I am incorporating ReactJS into a Laravel blade file. To get started, I included the React CDN and began writing code within the script tag. Everything seems to be going smoothly so far, however, I have encountere ...

Ways to access dropdown menu without causing header to move using jQuery

Greetings everyone, I am currently working on a dropdown language selection feature for my website. The issue I am facing is that when I click on the language dropdown in the header, it causes the height of the header to shift. $('.language- ...

Access the Vue instance from a different element instance

I've developed a leaflet map using vue.js. There's a method I've created called 'showSubmit' that needs to be triggered on the leaflet marker moveend event. Here's what I'm currently doing: this.map.markers.user.on("move ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

Encountered a runtime error while processing 400 requests

Current Situation: When authenticating the username and password in my Ionic 2 project using WebApi 2 token authentication, a token is returned if the credentials are correct. However, a 400 bad request error is returned if the credentials are incorrect. ...

Unintended repetition with fetch() for loading a texture

I've been experimenting with using the fetch statement to fetch a local image and incorporate it into my (three.js) project. However, I seem to have created an infinite loop and I can't figure out why. Since the project is quite large, I've ...

What is the best way to launch a Popup window that spans from the top to the bottom of the screen?

I'm attempting to create a popup window that stretches from the top of the screen to the "applications" bar in Windows. Here's the code I'm using: function windowOpener(windowHeight, windowWidth, windowName, windowUri) { var windowHeight = ...

Unable to dynamically insert values into a JSON object

My goal is to populate a JSON object with objects that look like this: var books = [{ "no" : 1, "bookType":"fiction", "bookPrice": 60 },{ "no" : 2, "bookType":"f ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

Utilizing async await to manage Promise { <Pending> } with an Express API

I have an API controller that retrieves a list of doctors: exports.doctorsList = async (req, res) => { const users = await User.find().exec(); let responseArray = await users.map(async (user) => { const transactions = await MedicalCon ...

The operation cannot be completed due to lack of authorization on the specified database

Recently, I've been encountering a not authorized error randomly on my production server. Here's the rundown of my setup: MongoDB 3.2.1 Mongo (ruby driver) 2.2.3 Mongoid 5.1.1 bson 4.0.2 In my mongoid.yml file, I haven't configured any us ...

"Retrieving Data Using jQuery's .ajax Method in Visual Basic

<WebMethod()> Public Shared Function gtet() As String ... Dim GET = uClass.GetSets(dbuser, dbparam1) ... End Function and $(document).ready(function () { data = { }; var jsondata = $.toJSON(data); $.ajax({ type: "GET ...

Express seems to be unable to read the request body

Recently delving into node and express, I was progressing well with my understanding of post requests. Initially, everything worked smoothly as I created new documents in my MongoDB database. However, today I encountered a peculiar issue. https://i.sstati ...