12

I have a model that keeps erroring out after the first POST. I'm creating a scheduling application, which is X number of days, with rooms, and time slots for the rooms.

The issue I'm having is creating Day Objects in the database. For sake of easy reading I'm just going to have a single key value pair

day.model.js

var mongoose = require('mongoose');

// Day Schema
var daySchema = mongoose.Schema({
  name:{
    type: String,
    required: true,
  },
  createdAt:{
    type: Date,
    default: Date.now
  }
});

var Day = module.exports = mongoose.model('Day', daySchema);

// Get all Days
module.exports.getDays = function(callback, limit){
  Day.find(callback).limit();
};

// Add Day
module.exports.addDay = function(day, callback){
  var add = {
    name: day.name,
};
Day.create(add, callback);
};

day.routes.js

var express     = require('express');
var router      = express.Router();
var jwt         = require('jsonwebtoken');
var config      = require('../config/database');

Day = require('../models/day.model.js');

// Get all Days
router.get('/', function(req,res){
  Day.getDays(function(err, days){
    if(err){
      res.send(err);
    }
    res.json(days);
  }); 
});

// Add Day
router.post('/create', function(req,res){
  var day = req.body;
  Day.addDay(day, function(err, day){
    if(err){
      res.send(err);
    }
    res.json(day);
  });
});

module.exports = router;

Example JSON

  1. {"name": "Monday"}- this will reflect in the Database just fine
  2. {"name": "Tuesday"} - this will throw an 11000 error

Error

{
  "code": 11000,
  "index": 0,
  "errmsg": "E11000 duplicate key error collection: <collection-name>.days index: date_1 dup key: { : null }",
  "op": {
    "name": "Tuesday",
    "_id": "57fd89638039872dccb2230b",
    "createdAt": "2016-10-12T00:52:51.702Z",
    "__v": 0
  }
}

Where I'm confused is I have this same setup for a User but when it comes to making a new Day, this duplicate key error arises. Not sure what I'm missing or doing wrong. Thanks

wsfuller
  • 1,810
  • 8
  • 31
  • 49

6 Answers6

31

I think You had model for days collection with date attribute which had unique index date_1.

Now You've removed it but collection still has that index.

so that's why it says:

duplicate key error collection: .days index: date_1 dup key: { : null }

it means You're inserting another record where date attribute is also null.

log in to mongodb from console and try to do this:

db.collectionNameHere.getIndexes();
db.collectionNameHere.dropIndex('date_1');
db.collectionNameHere.getIndexes();

p.s. feel free to provide any additional data in Your question or in comments, to help me/us to solve Your issue.

num8er
  • 18,604
  • 3
  • 43
  • 57
  • 3
    So looks like there were a bunch of Indexes in the collection that have gotten polluted over development time. I had dropped the collection with Robomongo right before this, but looks like it still retained those indexes. Thanks for the help and extremely clear answer. – wsfuller Oct 12 '16 at 01:48
  • @Full-Hybrid happy that was helpfull (; – num8er Oct 12 '16 at 01:52
  • Hi, @num8er Do we need to drop indexes every time.. Is It a Correct solution? – Ravi Sharma Oct 08 '21 at 11:46
  • @RaviSharma of course not. It’s situational. Better use robo3t or whatever and manage indexes correctly – num8er Oct 08 '21 at 11:49
2

drop the collection and run again

1

Although the answer from @num8er is totally correct, but an easier approach to do that is: Go to your MongoDB collections => you will have the indexes tab, when you go to that tab you will see the different index rows that you have created, and then just push the Drop Index button of the rows you don't want or just drop all of them and start again.

Kim-Jun-Un
  • 83
  • 2
  • 11
1

I have also faced the same error.

E11000 duplicate key error collection: mydb.users index: token_1 dup key: { token: null }

Example

Answer - I simply drop the collection from the database. Then I post some data, and it's working fine.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

You should delete your entire collection and try again. That is why, MongoDB keeps track of your previoues state.

-2

I had similar issue and ran into this question and got to read the comment above me. I thought he was trolling at first but I had an epiphany that is difficult to explain. I dropped the collection and store new documents and miraculously the errors are now gone. Maybe it's some mongodb bug, I'm not sure really.