我在尝试插入子文档时收到MongoDB错误. subdocs已经具有唯一的_id,但是对于我不想要唯一的不同的非唯一字段,会抛出错误.
原文链接:https://www.f2er.com/angularjs/143622.htmlAngular中的错误是:“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