Please help with decoding key _id to primitive.ObjectID in go

Your issue is likely due to the way you’re inserting the document into MongoDB. Since the User struct has ID of type primitive.ObjectID, but you’re not explicitly setting it when inserting, MongoDB generates an _id field of type ObjectID automatically. However, your user struct lacks an ID field during insertion, which means MongoDB might be storing _id in an unexpected format.

Solution

1. Ensure ID is set before inserting

Modify the User struct instance before inserting it:

user := auth.User{
	ID:           primitive.NewObjectID(), // Generate a new ObjectID
	Username:     "anyuser",
	PasswordHash: "somehash",
	Permissions:  auth.NewPermissions(auth.PermissionUser),
}

This ensures that _id is stored as a primitive.ObjectID.

2. Use bson.M{} or bson.D{} for querying

Your query bson.D{} (empty filter) should work, but to be explicit, try:

singleResult := usersCollection.FindOne(ctx, bson.M{"username": "anyuser"})

This ensures you’re fetching a document that exists.

3. Check Decoding Again

After making the above changes, try decoding again:

var userResult auth.User
if err := singleResult.Decode(&userResult); err != nil {
	panic(err)
}
fmt.Println("User retrieved:", userResult)

Explanation of the Error

  • The error message cannot decode objectID into an array suggests that MongoDB might be returning an _id of a different type or an unexpected structure.
  • MongoDB automatically assigns an _id field as ObjectID when not explicitly set.
  • If you inserted a document without ID, MongoDB might be handling _id in a way that Go’s BSON decoding doesn’t expect.
1 Like