我有一个名为city的猫鼬模式,其中一个自动递增字段称为“ id” ,该模式包含另一个具有自动递增模式的数组,称为“ marker” 。问题是,当我插入没有标记的城市时,出现此错误:
BulkWriteError:E11000重复键错误集合: bd.cities索引:markers.id_1 dup键:{:null}
我试图使用稀疏属性并捕获未保存的城市预保存并设置标记数组未定义,但是我真的被这个错误所困扰。
城市模式:
let mongoose = require('mongoose');
let autoIncrement = require('mongoose-auto-increment');
let Marker = require('./marker');
var MarkerSchema = require('mongoose').model('marker').schema;
let citySchema = mongoose.Schema({
id: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
status: {
type: Number,
required: true
},
coordinates: {
latitude: {
type: Number,
required: true
},
longitude: {
type: Number,
required: true
}
},
markers: [MarkerSchema]
});
citySchema.pre('save', function (cb) {
if (this.markers && this.markers.length === 0) {
console.log('no markers')
this.markers = undefined;
}
cb();
});
citySchema.plugin(autoIncrement.plugin, {
model: 'city',
field: 'id',
startAt: 1,
incrementBy: 1
});
let City = module.exports = mongoose.model('city', citySchema);
标记架构:
let mongoose = require('mongoose');
let autoIncrement = require('mongoose-auto-increment');
let markerSchema = mongoose.Schema({
id: {
type: Number,
required: true,
unique: true,
sparse: true
},
status: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
coordinates: {
latitude: {
type: Number,
required: true
},
longitude: {
type: Number,
required: true
}
}
});
markerSchema.plugin(autoIncrement.plugin, {
model: 'marker',
field: 'id',
startAt: 1,
incrementBy: 1
});
let Marker = module.exports = mongoose.model('marker', markerSchema);