Mongodb error occurred due to a duplicate key in the collection with the key value set

I need to set up multiple user accounts.

The first account creation is successful, but I encounter an error when trying to create a new account:

BulkWriteError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: db.users.$friends.userid_1  dup key: { : null }
    

The initial user's details are correct, with an empty array for friends as intended.

However, I encounter issues when creating subsequent users.

How can I resolve this error?

The section of the user schema related to friends in users is as follows:

   friends : [
        {
            userid : {type: String, default: '', unique: true },
        }
    ],
    friendRequests: [
        {
            userid : {type: String, default: '', unique: true },
        }
    

EDIT:

I have referred to https://docs.mongodb.com/manual/core/index-unique/#unique-index-and-missing-field but have not been able to resolve the issue.

EDIT2:

There are no friends or friend requests created by default.

EDIT3:

Here is the complete code:

passport.use('local-signup', new LocalStrategy({
                usernameField : 'username',
                passwordField : 'password',
                passReqToCallback : true,
            },
            function(req, username, password, done) {
                process.nextTick(function() {
                    console.log("doing local signup");
                    username = username.toLowerCase();
                    Account.findOne({username :  username }, function(err, user) {
                        var expr = "/admin/";
                        if (err) {
                            return done(err);
                        } else if (user) {
                            return done(null, false, 'That username is already taken.');
                        } else if(username.length < 3 || username.length >= 12) {
                            return done(null, false, 'Username has to be between 3 and 12 characters! :( '  + username);
                        } else if(/^[a-zA-Z0-9- ]*$/.test(username) == false) {
                            return done(null, false, 'You cant have any special characters!');
                        } else if(password.length < 5 || password.length > 15) {
                            return done(null, false, 'Password need to be 5-15 characters long!');
                        } else {
    
                            var newUser            = new Account();
                            newUser.username    = username;
                            newUser.password = newUser.encryptPassword(password);
                            newUser.save(function(err) {
                                if (err)
                                    throw err;
                                return done(null, newUser);
                            });
                        }
                    });
    
                });
    
            }));
    

User Model:

var mongoose     = require('mongoose');
    var Schema       = mongoose.Schema;
    var passportLocalMongoose = require('passport-local-mongoose');
    var bcrypt   = require('bcrypt-nodejs');
    
    
    
    var UserSchema   = new Schema({
        username: {type: String, index: { unique: true }},
        password: {type: String},
        salt: { type: String},
        hash: {type: String},
        gender : {type: String, default: 'male'},
        friends : [
            {
                userid : {type: String, default: '', unique: true },
            }
        ],
        friendRequests: [
            {
                userid : {type: String, default: '', unique: true },
            }
        ]
    
    });
    UserSchema.methods.encryptPassword = function(password) {
        return bcrypt.hashSync(password, bcrypt.genSaltSync(10));
    }
    
    UserSchema.methods.validPassword = function(password) {
        return bcrypt.compareSync(password, this.password);
    }
    
    
    
    module.exports = mongoose.model('Users', UserSchema);
    

Answer №1

It has been observed that MongoDB does not enforce uniqueness in array values within a single document, as mentioned in this comment.

Therefore, the uniqueness in the array needs to be managed in the client code. You can implement a combination of strategies to meet this requirement.

Firstly, remove the unique index and utilize the Mongoose unique array plugin to have Mongoose validate the uniqueness in the array during document creation/update.

This plugin is designed to work with both scalar and document arrays. For your scenario, you can make the following adjustments:

var uniqueArrayPlugin = require('mongoose-unique-array');
UserSchema.plugin(uniqueArrayPlugin);

By doing this, validation will be enforced through a validator and you should receive a validation message when performing update/save operations.

It is important to note that the unique plugin does not function properly when using $push in an update query.

Instead, you can approach it like this:

Account.findOne({"friends.userid":{"$ne":inputuserid}}, {"$push":{"friends":new user doc}});

For further information, you can refer to the blog and review the usage examples provided by the author.

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

Having trouble making a basic delete request in Postman

Looking for assistance with a phonebook app built using node.js, express, mongo db, and mongoose. Currently, Get and Post requests are functioning properly, with Post requests being saved in the Mongo database. However, encountering issues with Delete re ...

Why hasn't the styles folder been generated in Nuxt 3?

After running the command "npx nuxi generate," the css folder does not seem to be created in the static site. What could be the issue? package.json: { "private": true, "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": ...

Having trouble transferring data between Vue.JS components

Wondering how to pass data from the parent component (Home route) to the child component (playlist route) using props? Encountering a "TypeError: Cannot read property 'length' of undefined" error in the child component? These two components are c ...

Determine the total count of files in queue with Uploadify prior to initiating the upload process

When I specify auto: false in the uploadify settings, the upload process will only start when the submit button is clicked. Once the onQueueComplete event is triggered, the form will be submitted. However, if no files are selected, the onQueueComplete even ...

Is there a way to showcase my information on flash cards using JavaScript?

Currently, I am developing a full stack application that utilizes JavaScript on both the front and back end. This application allows users to create their own flashcards set. Upon clicking "View Cards," the data is fetched and the question-answer pair is d ...

Is there a method to iterate through an HTML quiz in order to extract text from "label for" with the value of "true"?

I need assistance with extracting all the correct answers from a multiple choice radio button quiz. The correct answers are identified by the attribute value="true" in the HTML code. Is there a way to iterate through and retrieve the text of all the corr ...

Angular: Enhancing View Attribute by Eliminating Extra Spaces

I'm using an ng repeat directive to dynamically set the height in my code. <ul> <li ng-repeat="val in values" height-dir >{{val.a}}</li> </ul> app.directive('heightDir',function(){ return { restrict: ' ...

Tips for emphasizing specific text within HTML tags without highlighting the tags in Vue

I am using a tag with v-html to render HTML text and display it, like so: <div v-html="htmlText"></div> I have written code to highlight text and it works on regular text: Vue.filter('highlight', function (word, query) { ...

Node JS excels in its ability to handle non-blocking operations

In my database query method, I created a function called getParam(). Here is how it looks: function getParam(tableName, paramName, id){ var param=0; var query = client.query('SELECT '+ paramName + ' AS myparam FROM ' + tableName + &ap ...

What are the techniques used to minimize JavaScript functions?

Is there a more efficient way to reduce the amount of JavaScript code needed for functions that share the same call procedure? I'm struggling to find a clear explanation but here's the code snippet below... JavaScript: $(function() { $( &a ...

Json data integrated dropdown menu

I have successfully retrieved data from a Json array and displayed it in a dropdown list. However, I am facing an issue where I want to only show the name of the city instead of both the name and description. If I remove cities[i]['description'], ...

Is it possible to use JavaScript to click on a particular point or element within a canvas?

Is there a way to trigger a click at a specific point on a canvas without direct access to the code that generates it? I've attempted using coordinates, but haven't had any success. Any alternative suggestions would be appreciated. UPDATE: To pr ...

The Vue.js input for checkboxes and radios fails to toggle when both :checked and @input or @click are used simultaneously

Check out this example on JSFiddle! <script src="https://unpkg.com/vue"></script> <div id="app"> <label> <input type="checkbox" name="demo" :checked="isChecked" @input=" ...

Updating the rotation of a grandchild in Three.js Object3D

In my current project, I am attempting to make the grandchild of a rotated Object3D element face towards the camera using the lookAt() method. I have experimented with various approaches to achieve this. However, the source code for the Object3D.lookAt() ...

Have Babel transpile configuration files into CommonJS format

I'm having trouble getting my Nuxt app to work with Jest for testing. I have a setupFilesAfterEnv property set with a setupTests.ts file that imports a translation file. The translations file uses ES6 import/export module syntax, but it seems like my ...

`The Issue with Ineffective Slider Removal`

Below is the complete code: import React, { Component } from "react"; import "./App.css"; import Slider from "@material-ui/core/Slider"; import Typography from "@material-ui/core/Typography"; class App extends Compo ...

Can all browser console messages and errors be sent to a different machine using a pipeline?

Currently, I am in the process of troubleshooting a javascript error that is occurring within a Cordova app's InAppBrowser on an Android device. Despite being able to connect to the web-view on the phone using Chrome's remote debugging tools, the ...

Tallying outcomes using JavaScript

I encountered a particular challenge: I have designed a table for user interaction, with results displayed at the end of each row. Just out of curiosity, I would like to count how many results are present in the table without performing any calculations. I ...

Encountering trouble with displaying data in Express and Mongoose

Struggling to comprehend how to define and utilize an API in Express, while using Mongoose to connect with MongoDB. Successfully saving objects from input on the front end, but getting lost when it comes to retrieving and displaying the saved data. Take a ...

Incorporating a JavaScript file into Angular

I'm looking to incorporate a new feature from this library on GitHub into my Angular project, which will enhance my ChartJS graph. @ViewChild('myChart') myChart: ElementRef; myChartBis: Chart; .... .... const ctx = this.myChart.nativeEleme ...