Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

angularjs - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...