angularjs – Mongo在非唯一字段上给出“重复键错误”

我在尝试插入子文档时收到MongoDB错误. subdocs已经具有唯一的_id,但是对于我不想要唯一的不同的非唯一字段,会抛出错误.

Angular中的错误是:“Assets.serial已经存在”.如何使此字段包含重复值,以及导致模型假设它应该是唯一的?

这是我的Mongoose模型:

'use strict';

var mongoose = require('mongoose'),Schema = mongoose.Schema;
var AssetUrlSchema = new Schema({
  name: {
    type: String,unique: false,default: '',trim: true
  },url: {
    type: String,default: 'http://placehold.it/75x75',}),AssetSchema = new Schema({
  serial: {
    type: Number,unique: false
  },urls: {
    type: [AssetUrlSchema],default: [
      { name: '',url: 'http://placehold.it/75x75' },{ name: '',url: 'http://placehold.it/75x75' }
    ]
  }
}),/**
 * Item Schema
 */
ItemSchema = new Schema({
    name: {
        type: String,required: 'Please enter name',trim: true
    },assets: {
    type: [AssetSchema],default: [],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);

这是我的“保存”方法

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;
        }
      );
    }

我第一次插入文档时,它工作正常.随后的任何时间都会失败,因为assets.serial字段不是唯一的.但是,我特意将该字段标记为唯一:false.

模式控制台中的错误是:

{ [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不会删除现有索引,因此您需要显式删除索引才能删除它.在shell中:
> db.items.dropIndex('assets.serial_1')

如果您最初将该字段定义为唯一,则会发生这种情况:true但稍后将其从架构定义中删除或将其更改为unique:false.

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...