skip to content
Alvin Lucillo

ObjectID or string

/ 1 min read

Using either ObjectID and string types for the primary key of a mongodb document works, but you should decide this before a document is created. This is to prevent unmarshalling issues due to different types used by documents in a collection. Note that mongodb allows mixed types, so it should be your app’s responsibility to ensure consistency.

type (
	struct1 struct{
		ID primitive.ObjectID `bson:"_id"`
	}
	struct2 struct{
		ID string `bson:"_id"`
	}
)