Error code E11000 is thrown due to a duplicate key in a Node.js application

Whenever I input data on the webpage, it syncs correctly with the database. However, when I attempt to fill out the same form again, an error occurs:

{
    "code": 11000,
    "index": 0,
    "errmsg": "E11000 duplicate key error collection: test.creates index: aname_1 dup key: { : \"MicroSoft\" }",
    "op": {
        "aname":"MicroSoft",
        "pname":"Bing",
        "pusername":"Debtanu",
        "_id":"57c9486d690a35fc21794169",
        "__v":0
    }
}

After clearing everything from the database and attempting to fill out the same form again, it accepts the entry. So why does it not accept the next entry in the same Account form?

Below are excerpts from my app.js and Account.jade file.

app.js:

var express = require('express');
 var favicon = require('serve-favicon');
 var path = require('path');
 var logger = require('morgan');
 var cookieParser = require('cookie-parser');
 bodyParser = require('body-parser');
 var session = require('express-session')
 var mongoose = require('mongoose');
 var nodemailer = require('nodemailer');
 var passport = require('passport');
 var LocalStrategy = require('passport-local').Strategy;
 var bcrypt = require('bcrypt-nodejs');
 var async = require('async');
 var crypto = require('crypto');
 var flash = require('express-flash');
 var router = express.Router();
 var fs = require('fs');


var createSchema = new mongoose.Schema({
    cname: {type: String, unique: true, sparse: true},
    aname : {type: String, unique: true, sparse: true},
    ausername : String,
    pname : {type: String, unique: true, sparse: true},
    pusername : String
});


var Create = mongoose.model('Create', createSchema);

mongoose.connect('localhost');

var app = express();


// Middleware
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
    secret:'keyboard cat',
    // connect-mongo session store
    proxy: true,
    resave: true,
    saveUninitialized: true
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname,'/public')));
app.use('/img',express.static(path.join(__dirname, 'public/images')));




app.get('/Account', function(req, res) {
    res.render('Account', {
        user: req.user 
    });
});

app.post('/Account', function(req,res,next){
    var create = new Create({
        cname: req.body.cname,
        aname: req.body.aname,
        ausername: req.body.ausername
    });

    create.save(function(err, doc){
        if(err) res.json(err)
        else res.redirect('/home');
    });
});

// Server
app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});

module.exports = app;

A note that account.jade is not formatted correctly

Answer №1

By defining aname as a unique field in the Schema, you are restricting the database to only store unique values for that field. The same rule applies to cname and pusername.

In this scenario, if you try to save "MicroSoft" for the first time, it will be successfully stored in the database. However, if you attempt to save "MicroSoft" again, MongoDB will throw an error since the value already exists in the database.

To resolve this issue, you have two options: either remove the unique constraint or ensure that you are saving only unique values for these fields.

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

Traverse JSON data using associative loops

Is there a way for me to iterate through this JSON data without using numerical indexes? I want to treat it like an associative array. This is what I have so far: $.post('/controlpanel/search', { type: type, string: string }, function(data){ ...

The auto-refresh feature of DataTables is not functioning as expected

Having trouble with the reload feature of DataTables. This is the code I'm using to load and reload the table on the server-side: $( document ).ready(function() { $('#dienst_tabelle').DataTable( { "ajax": "getData ...

Creating a searchable and filterable singleSelect column in the MUI DataGrid: A step-by-step guide

After three days of working on this, I feel like I'm going in circles. My current task involves fetching data from two API sources (json files) using the useEffect hook and storing them in an array. This array contains a large number of products and a ...

Tips for effectively managing loading state within redux toolkit crud operations

Seeking guidance on efficiently managing the loading state in redux-toolkit. Within my slice, I have functionalities to create a post, delete a post, and fetch all posts. It appears that each operation requires handling a loading state. For instance, disp ...

Creating dynamic values in data-tables using Vuetify

As I work with JSON data, my current task involves formatting it using Vuetify's Data Tables. The official documentation provides guidance on defining table headers as shown below: import data from './data.json' export default { data ...

Attempting to flip the flow of marquee loop in javascript

I am currently modifying this code to create a left-to-right marquee instead of the original right-to-left one. However, after successfully changing the direction, the text no longer loops as it did originally. I'm stuck and can't seem to figure ...

Tips for adding multiple entries to a TransactionWould you like to know

I have a question regarding SQL Server transactions I need to insert data into both Table_A and Table_B. Table_B includes a key from Table_A, and the number of records in Table_B with the Table_A key can vary. [Table_A] id: , title: [Table_B] ...

HTML: Ensure that a user fills out a minimum of one text box before submission

<tr><td> First Name: </td><td><input type="text" name="FirstName" required></td> </tr> <tr><td> Last Name: </td><td><input type="text" name="LastName" required> </td></tr> ...

How can I retrieve the index of a v-for loop within a function in Vue.js HTML?

How can I splice the array from the fields in HTML Vue JS if the status is true? I also need to pass the index value to a function. Is this possible? The error I am encountering is: Uncaught ReferenceError: index is not defined at Object.success (80 ...

Jquery: Pressing Enter will cause the input field to lose

Take a look at this fiddle I created: http://jsfiddle.net/7wp9rs2s/. This is the progress I have made on my project so far. In the fiddle above, you can double click on one of the 4 items and a textbox will appear for editing. Instead of clicking out of t ...

An error is triggered when using db.listCollections() in an ExpressJS environment

I am currently working with ExpressJs and MongoDB, but I've encountered an issue with the following code: var db = monk(DB_URL); app.use(function (req, res, next) { req.db = db; next(); }); app.get("/view_collections", function (req, res) { ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...

Validator alert for AMP scripts

I have implemented the amp version for my content management system. Since each article has a different body, some include amp-instagram while others include amp-facebook, and so on. In order to cover all bases, I have added both amp-facebook and amp-inst ...

Confirm whether the Iterator type is the same as the AsyncIterator type

Is there a clever JavaScript technique to differentiate between Iterator and AsyncIterator without initiating the iteration process? I'm attempting to create a type checker like this: function isAsyncIterator<T>(i: Iterator<T> | AsyncIter ...

Sending back an HTTP response code from PHP to AJAX

I'm currently working on creating a login page for a website. The functionality involves using AJAX to send a request to a PHP script that verifies the username and password input. If the query returns a successful result, I use http_response_code(200 ...

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Retrieving data from MongoDB and saving it to your computer's hard drive

I've asked a variety of questions and received only limited answers, but it has brought me this far: Mongoose code : app.get('/Download/:file(*)', function (req, res) { grid.mongo = mongoose.mongo; var gfs = grid(conn.db); var fi ...

Rails: Ensure that JSON form fields remain populated in case the form encounters a validation error

I am using a rails simple form to create a product with three fields inside in order to associate it with appropriate categories: <div class="form-group"> <%= f.input :child_category_id, :collection => @categories.order(:name), :l ...

Contrast between v-for arrangements

Would anyone be able to clarify the distinction between these two v-for structures? <li v-for="item in items" :key="item"> </li> and <li v-for="(item, i) in items" :key="i"> </li> ...