It's the old E11000 error but with a twist (and yes I searched and found many of the same question but without the exact details that apply here - mainly the explicit _id
assignment).
I'm manually assigning the _id
field with bson.NewObjectId()
because I need to return the ID back to the client - this was based on discussions from SO and GitHub, for example: https://github.com/go-mgo/mgo/issues/453
https://github.com/Southclaws/ScavengeSurviveCore/blob/master/storage/player.go#L28-L32
The ID field is set up in the struct as:
ID bson.ObjectId `json:"_id" bson:"_id"`
https://github.com/Southclaws/ScavengeSurviveCore/blob/master/types/player.go#L9-L23
So far I don't think I've missed anything. Unit tests create 3 instances of this object one after the other:
https://github.com/Southclaws/ScavengeSurviveCore/blob/master/server/handler_admin_test.go#L21-L56
First one gets created fine, it has an _id
assigned to it (checked via mongo-express) and I even printed out the ID right before .Insert
was called, same ID, everything is fine:
CREATING {ObjectIdHex("5b092f4aff3055468e3ce00a") playerID1 (...)
Problem arises when the next of the three test records gets inserted - exact same code, and the log is printed:
CREATING {ObjectIdHex("5b092f4aff3055468e3ce00b") playerID2 (...)
but it returns an E11000:
E11000 duplicate key error collection: <db>.<collection> index: <collection>_id_1 dup key: { : null }
From what I can gather, it thinks _id
is null but given all the evidence I can see, it's not null at all because bson.NewObjectId()
is assigned to the _id
field right before .Insert
is called - and the object is printed out right before insertion and the ID is there.
What am I missing here?