angularjs – Mongo在非唯一字段上给出“重复键错误”
发布时间:2020-12-17 07:56:39 所属栏目:安全 来源:网络整理
导读:我在尝试插入子文档时收到MongoDB错误. subdocs已经具有唯一的_id,但是对于我不想要唯一的不同的非唯一字段,会抛出错误. Angular中的错误是:“Assets.serial已经存在”.如何使此字段包含重复值,以及导致模型假设它应该是唯一的? 这是我的Mongoose模型: 'u
我在尝试插入子文档时收到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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读