Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo Giving 'duplicate key error' on non-unique fields

I am getting a MongoDB error when trying to insert a subdocument. The subdocs already have unique _ids, but an error is being thrown for a different, non-unique field that I don't want unique.

The error in Angular is: "Assets.serial already exist". How can I make this field contain duplicate values, and what is causing the model to assume it should be unique?

Here is my Mongoose model:

'use strict';

var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var AssetUrlSchema = new Schema({
  name: {
    type: String,
    unique: false,
    default: '',
    trim: true
  },
  url: {
    type: String,
    unique: false,
    default: 'http://placehold.it/75x75',
    trim: true
  },
}),

AssetSchema = new Schema({
  serial: {
    type: Number,
    unique: false
  },
  urls: {
    type: [AssetUrlSchema],
    unique: false,
    default: [
      { name: '', url: 'http://placehold.it/75x75' },
      { name: '', url: 'http://placehold.it/75x75' }
    ]
  }
}),

/**
 * Item Schema
 */
ItemSchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Please enter name',
        trim: true
    },

  assets: {
    type: [AssetSchema],
    default: [],
    unique: false
  },

  property: {
    type: Schema.ObjectId,
    zd: 'Please select a property',
    ref: 'Property'
  },

    created: {
        type: Date,
        default: Date.now
    },

    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});

mongoose.model('Item', ItemSchema);

And here is my 'save' method:

function(){
      var i = 0, assets = [];

      for (;i < 24;i++) {
        assets.push({
          serial: 1000+i,
          urls: {
            name: 'Asset Name ' + i,
            url: 'http://placehold.it/75x75?'
          }
        });
      }

      item = new Items ({
        name: 'FPO',
        property: newPropId,
        assets: assets
      });

      return item.$save(
        function(response){ return response; },
        function(errorResponse) {
          $scope.error = errorResponse.data.message;
        }
      );
    }

The first time I insert a document, it works fine. Any subsequent time, it fails with a 400 because the assets.serial field is not unique. However, I am specifically marking that field as unique:false.

The error in the mode console is:

{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: mean-dev.items.$assets.serial_1  dup key: { : 1000 }]
name: 'MongoError',
code: 11000,
err: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: mean-dev.items.$assets.serial_1  dup key: { : 1000 }' }
POST /api/items 400 14.347 ms - 41
like image 401
Brandon James Avatar asked Feb 27 '15 21:02

Brandon James


People also ask

How do I fix duplicate key errors?

There are the following options for handling duplicate key errors: You can delete the file, for example if you know that there are values in the file that are not correct. You can then adjust the file and upload it again. The system will not transfer any data from files that contain duplicate instances.

How do I avoid duplicate errors in Mongodb?

If you ever faced this error all you need to do is to check your model carefully and find out that is there any unique key set true by you and if it is not necessary then simply remove the unique key from the model or otherwise set a unique value if it is necessary to be unique.

What is __ V in Mongodb?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).


1 Answers

Mongoose doesn't remove existing indexes so you'll need to explicitly drop the index to get rid of it. In the shell:

> db.items.dropIndex('assets.serial_1')

This will happen if you initially define that field unique: true but then later remove that from the schema definition or change it to unique: false.

like image 52
JohnnyHK Avatar answered Oct 11 '22 16:10

JohnnyHK