node.jsmongodbc9.io

How to fix and prevent duplicate key error in mongodb


I've been working on a hobby project recently and I've encountered a problem I can't seem to figure out, even after scouring the internet for an answer. I'm using Node.js on c9.io with MongoDB. Anytime I try to create a new entry into the database, the first entry works and goes through fine, but then the second one causes an error.

E11000 duplicate key error collection: project.tasks index: username_1 dup key: { : null }'

My Schema:

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var taskSchema = new mongoose.Schema({
    task: String,
    region: String,
    cost: String,
    when: String,
    isAccepted: Boolean,
    author: {
        id:{
            type: mongoose.Schema.Types.ObjectId, 
            ref: "User"
        }
    },
    tasker: {
        id : { 
          type: mongoose.Schema.Types.ObjectId,
          ref: "User"
        }
    }
}); 

taskSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Task", taskSchema);

My Post Request:

app.post("/taskers/index/show", function(req, res){
   var task = req.body.task;
   var newTask = {
      task: task.task, 
      region: task.region, 
      cost: task.cost, 
      when: task.when, 
      isAccepted: false, 
      author: req.user._id, 
      tasker: req.user._id
   };
   console.log("STSOTSOTSOTOOPP");
   Task.create(newTask, function(err, newlyCreated){
      if(err){
         console.log(err);
      } else {
         console.log(newlyCreated);
         res.redirect("/users/index");
      }
   });
});

If anyone knows what I'm doing wrong or can lead me to a solution, that would be amazing as I've been stuck on this for a while.


Solution

  • E11000 duplicate key error collection: project.tasks index: username_1 dup key: { : null }

    This error is coming from mongo (not from mongoose). Removing indexes from your mongoose schema will not have any impact on the underlying collection so you'll now want to remove the unique index on username from your tasks collection.

    This index was likely created by previous code that we no longer see (or perhaps by that taskSchema.plugin(passportLocalMongoose); -- that sounds suspiciously like the kind of thing that would want an index on username).

    If you connect to mongo using the shell, you should be to run db.tasks.getIndexes() to see that unique username index, and then use the dropIndexCommand to remove the offending index.

    See E11000 duplicate key error index in mongodb mongoose for more details about how mongoose & mongo interact.