Mongo Giving 'duplicate key error' on non-

2019-01-19 23:00发布

问题:

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

回答1:

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.