What is the reason behind MongoDB's decision to permit the creation of duplicate users

I'm currently facing an issue while trying to register a new user through my Angular app. Even though I've set the name field as unique in Mongo, when I attempt to register a user with an existing username, it allows me to do so without returning an error. This results in multiple users with the same name in the database.

Here's a snippet of the API:

apiRoutes.post('/signup', function(req, res) {
    if (!req.body.userId || !req.body.password) {
        res.json({success: false, msg: 'Please pass name and password.'});
    } else {
        var newUser = new User({
            name: req.body.name,
            password: req.body.password,
            wallet: req.body.wallet,
            userPic: req.body.userPic
        });
        // save the user
        newUser.save(function(err) {
            if (err) {
                return res.json({success: false, msg: 'Username already exists.'});
            }
            res.json({success: true, msg: 'Successful created new user.'});
        });
    }
});

Below is the model code:

// set up a mongoose model
var UserSchema = new Schema({
    name: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },

    wallet: {
        type: Number,
        required: true
    },

    userPic: {
        type: String,
        required: true,
        unique: true
    }

    });

Lastly, here's the POST request code where user login and password are obtained from external sources:

 let newUser = {
      password: password,
      wallet: 0,
      userPic: md5(login),
      name: login
    };   
    this.$http.post('http://127.0.0.1:8080/api' + '/signup', newUser);

Answer №1

attempt this in your schema:

label: {
        type: String,
        index:{unique: true},
        required: true
    }

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

Conceal element with transparent overlay without affecting the background

Looking to add animation to a snippet where the login menu rolls out? Consider two methods: adjusting the left position of the login menu or using another div on top to slowly reveal the login menu after moving it. The challenge lies in maintaining trans ...

Enhancing mongo queries - deciding between using _id or traversing the entire collection

For my project, I am utilizing mongodb as the database. I am currently considering the best implementation for queries. Let's say I need to retrieve 10 documents out of a total of 1000 documents based on a specific condition (not id). Would it be mo ...

When using React, I noticed that adding a new product causes its attributes to change after adding another product with different attributes on the same page

Imagine you are browsing the product page for a Nike T-shirt. You select black color and size S, adding it to your cart. The cart now shows 1 Nike T-SHIRT with attributes color: black, size: S. However, if you then switch to white color and size M on the ...

Why is the observable I'm utilizing in this Angular 11 component returning as undefined?

Currently, I am working on implementing a promotions feature for an Angular 11 e-commerce application. I have developed a service that sends a get request and retrieves a JSON file containing the campaign's information. The Service: import { Injectab ...

Webpack converts 'import' statements to 'require'

I'm currently in the process of compiling my nodeJS project using webpack. Everything seems to be working correctly after compilation, but I've noticed that the imports are being changed to requires. This causes an error when trying to run index. ...

What is the best way to send a function or callback to a child process in Node.js?

In this scenario, imagine having a parent.js file with a method called parent var childProcess = require('child_process'); var options = { someData: {a:1, b:2, c:3}, asyncFn: function (data, callback) { /*do other async stuff here*/ } } ...

What methods can be used to continuously send data to another web page within my website using XMLHttpRequest()?

As I delve into working with node.js and express.js, my primary goal is to efficiently tackle a specific issue. One of the pages on my website is tasked with receiving location data in latitude var lat and longitude var long. The challenge at hand is to c ...

Is this considered standard behavior for Ajax requests? If it is, can you explain the reasoning

In my application, I am utilizing one controller to handle two different views. First is View A: <div id="landingzone" style="width:500; height:300;"> </div> <script type="text/javascript"> $.ajaxSetup ({ cache: false }); va ...

Is it possible to retrieve elements by their ID when the ID values are constantly changing?

I'm facing an issue with accessing dynamic IDs using `getElementById`. I require this value to perform random calculations involving different elements. MY CODE <div class="col-lg-4" v-for="data in datas"> <button class="btn btn-outline-d ...

What is the process for inserting a new item into a mongoose array?

I'm currently developing a confidential web application. Below is the layout I've created for the user. const itemsSchema = { name: String } const userSchema = new mongoose.Schema({ username: String, email: String, password: String, M ...

How can I apply styling to Angular 2 component selector tags?

As I explore various Angular 2 frameworks, particularly Angular Material 2 and Ionic 2, I've noticed a difference in their component stylings. Some components have CSS directly applied to the tags, while others use classes for styling. For instance, w ...

Disabling a button until the AngularJS http request is fully loaded: A step-by-step guide

When updating or submitting a form, I want the button to be disabled until the response from the server is complete. Similarly, during page loading, I need the button to remain disabled until all data has been loaded. Currently, in my code, the button rem ...

Combining various datasets with identical X values in a D3 bar graph

I'm currently working on creating a grouped bar chart to display performance test results using D3 for the first time. The X axis should represent parallelism, indicating the number of threads used, while the Y axis will show the duration in millisec ...

Integrating Mailchimp with MongoDB and Node.js

As of now, I am managing a database of users in MongoDB and my goal is to provide them with regular updates on new content available on a real-estate marketplace website on a daily basis. My plan is to send out email notifications to each user every day w ...

"Implement Twitter Bootstrap into the Yeoman project with the command

Today, I decided to give Yeoman a try for the first time. Not only that, but I also want to incorporate Bootstrap for some stylish CSS designs. After adding it to the dependencies and npm installing it, I can confirm its existence in node_modules. Now com ...

Exploring a JSON API structure with the help of jQuery

I am currently exploring the world of JSON API and attempting to extract some data. As a beginner, I find myself struggling to identify the exact value to use. Here is an example of the JSON API I am dealing with: [ {"lang":"english","visual":"<span ...

The use of jquery UI.js is causing issues with loading select menus dynamically

When attempting to load a dynamically loaded select menu on my page using Ajax/PHP, I encountered an issue where the jquery UI plugin prevented the data from loading. As a result, I was unable to see anything when changing the first select menu. Below is ...

Encountering numerous errors during npm installation in a react project

Struggling with React as I try to navigate through course files and run npm install, only to be bombarded with countless errors and warnings on every single file. I've double-checked my directory and ensured the presence of a json file. gyp ERR! ...

Using Next.js with Firebase emulators

I've been struggling to configure Firebase's V9 emulators with Next.js, but I keep running into the same error message. See it here: https://i.stack.imgur.com/Uhq0A.png The current version of Firebase I'm using is 9.1.1. This is how my Fir ...

Can Node.js create objects with functions dynamically?

My Node.js application interacts with another server app to retrieve information about instances of specific objects. This information is organized as a tree structure that includes details such as node type (method or property), method arguments, node ID, ...