蒙戈给予非唯一字段的重复键错误“ [英] Mongo Giving 'duplicate key error' on non-unique fields

查看:241
本文介绍了蒙戈给予非唯一字段的重复键错误“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图插入一个子文档的时候得到一个MongoDB的错误。该SUBDOCS已经有了独特的_ids,但被抛出了一个不同的,非唯一的字段,我不想独特的错误。

在角的错误是:Assets.serial已经存在。 我怎样才能让这个字段包含重复的值,是什么原因造成的模型假设它应该是唯一的?

下面是我的猫鼬模型:

 使用严格的;VAR猫鼬=要求('猫鼬'),
模式= mongoose.Schema;
VAR AssetUrlSchema =新模式({
  名称: {
    类型:字符串,
    独特之处:假的,
    默认:'',
    修剪:真
  },
  网址:{
    类型:字符串,
    独特之处:假的,
    默认:http://placehold.it/75x75',
    修剪:真
  },
}),AssetSchema =新模式({
  串行:{
    类型:数字,
    独特之处:假的
  },
  网址:{
    类型:[AssetUrlSchema]
    独特之处:假的,
    默认值:[
      {名称:'',网址:'http://placehold.it/75x75},
      {名称:'',网址:'http://placehold.it/75x75'}
    ]
  }
}),/ **
 *项目架构
 * /
ItemSchema =新模式({
    名称: {
        类型:字符串,
        默认:'',
        要求:'请输入名称',
        修剪:真
    },  资产:{
    类型:[AssetSchema]
    默认值:[],
    独特之处:假的
  },  属性:{
    类型:Schema.ObjectId,
    ZD:'请选择一个属性',
    裁判:财产
  },    创建:{
        类型:日期,
        默认:Date.now
    },    用户:{
        类型:Schema.ObjectId,
        参考:用户
    }
});mongoose.model('项目',ItemSchema);

这是我的保存方法:

 函数(){
      变种I = 0,资产= [];      对于(; I< 24;我++){
        assets.push({
          串行:1000 +我,
          网址:{
            名称:资产名称+我,
            网址:http://placehold.it/75x75?
          }
        });
      }      项目=新的项目({
        名称:FPO,
        属性:newPropId,
        资产:资产
      });      返回的项目。$保存(
        功能(响应){返回响应; },
        功能(errorResponse){
          $ scope.error = errorResponse.data.message;
        }
      );
    }

我第一次插入一个文件,它工作正常。随后的任意时间时,出现一个400,因为assets.serial场不是唯一的。但是,我特别标志着该领域独特:假

在模式的控制台的错误是:

  {[MongoError:insertDocument ::引起:: 11000 E11000重复键错误指数:$均值dev.items assets.serial_1 DUP键:{1000}]
名称:'MongoError',
code:11000,
错误:insertDocument ::由:: 11000 E11000重复键错误索引造成:均值dev.items $ assets.serial_1 DUP键:{:1000}'}
POST / API / 400项目毫秒14.347 - 41


解决方案

猫鼬不会删除现有的索引,所以你需要显式删除摆脱它的索引。在shell:

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

如果您最初定义字段此会发生独特:真正的但后来从架构定义删除或更改为独一无二的:假的

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

解决方案

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.

这篇关于蒙戈给予非唯一字段的重复键错误“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆