MongoDB – 尝试保存多个文档,导致模式ObjectId的重复键错误,尽pipe没有唯一的键集

我得到了这两个模式:

const Account = mongoose.model('Account', new Schema({ name: {type: String, default: '', required: true}, email: {type: String, default: '', unique: true, required: true}, hashed_password: {type: String, default: '', select: false, required: true}, role: {type: mongoose.Schema.Types.ObjectId, ref: 'Role', required: true}, organisations: [{type: mongoose.Schema.Types.ObjectId, ref: 'Organisation'}], updatedAt: {type: Date, default: null}, createdAt: {type: Date, default: new Date(), required: true} })); const Organisation = mongoose.model('Organisation', new Schema({ name: {type: String, default: '', required: true, unique: true}, email: {type: String, default: '', required: true}, accounts: {type: [{type: mongoose.Schema.Types.ObjectId, ref: 'Account'}], required: true, default: []}, declinedInvites: {type: [{type: mongoose.Schema.Types.ObjectId, ref: 'Account'}], default: []}, admins: {type: [{type: mongoose.Schema.Types.ObjectId, ref: 'Account'}], required: true, default: []}, updatedAt: {type: Date, default: null}, updatedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', default: null}, createdAt: {type: Date, default: new Date(), required: true}, createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', default: null, required: true} })); 

如果我将一个Organisation保存到数据库,然后尝试使用此路由保存另一个Organisation

 router.post('/organisations', auth.verifyToken, (req, res, next) => { const creator = req.decoded._doc._id; const organisation = new Organisation({ name: req.body.name, email: req.body.email, accounts: [creator], declinedInvites: [], admins: [creator], createdBy: creator }); organisation.save((err, organisation) => { if (err) { return next(err); } }); }); 

它会抛出一个错误,如:

 MongoError: E11000 duplicate key error collection: docs.organisations index: accounts_1 dup key: { : ObjectId('5a0d89e89141e410a9617746') } 

对于空数组declinedInvites ,它会抛出一个错误说同样的事情,但是:

 MongoError: E11000 duplicate key error collection: docs.organisations index: declinedInvites_1 dup key: { : undefined } 

我不明白这里发生了什么,为什么当我没有在模式中设置unique密钥时,它会抛出重复的键错误?

       

网上收集的解决方案 "MongoDB – 尝试保存多个文档,导致模式ObjectId的重复键错误,尽pipe没有唯一的键集"

就像@GrégoryNEUT指出的那样,如果你在模式中设置了一个unique键,然后删除它,那么索引仍然会在那里,就好像你还有unique键集。

解决方法是用这个命令简单地删除索引:

 db.items.dropIndex('some-index-path') 

或者在我的情况下,我运行我的自定义脚本刷新数据库,这解决了所有索引,这可能是一个问题,而不是必须运行它的每个索引。