sai_reddy
(Sai Reddy)
1
Hi, I’m getting a duplicate error when creating a new record.
Model
new Schema({
organisation_name: {
type: String,
unique: true,
required: true,
},
members: [
{
user_id: {
type: Schema.Types.ObjectId,
required: true,
unique: true,
ref: "User",
},
role:{
type:String
},
_id: false,
},
],
});
Creating a doc query
OrganisationSchema.create({
organisation_name,
members: [{ user_id: id, role: "owner" }],
});
Error
E11000 duplicate key error collection: pmt.organisations index: members.user_id_1 dup key: { members.user_id: ObjectId('12331231231') }
Thank You
santimir
(santi)
2
Indexed fields like user_id
can not be duplicated.
The same will happen if you run db.collections.insertOne({_id:1})
, because _id
is an index.
From the value it seems to have been created manually (members.user_id: ObjectId('12331231231')
).
What you should do is to have the user_id
value created automatically, and not accepting it from user input.
Maybe someone else can complete this with some extra help.
The MongoDB article for indexes is also quite good: https://www.mongodb.com/docs/manual/indexes/
sai_reddy
(Sai Reddy)
3
Yeah, I understood the issue.
It’s because of indexes, which create conflicts. so I resolved it by removing the index on that reference document.
and ‘12331231231’ this id is manually written while creating above issue
Thanks
1 Like
system
(system)
Closed
4
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.