0
type Student struct {
    ID           primitive.ObjectID   `bson:"_id,omitempty"`
    ...
    Users      []primitive.ObjectID `json:"users"`
    ...
}

I have this struct and I want to add to Users array. I'm doing this and I'm using Mongo-go-driver

// Filter for search
filter := bson.M{"_id": userID}

// Fields to update
update := bson.M{"$addToSet": bson.M{"users": ID}}

// Update the document
UsersCollection := GetUsersCollection()
UsersCollection.FindOneAndUpdate(context.Background(), filter, update, nil)

Can somebody tell me what I'm doing wrong? It's not adding to the database it's staying null.

1 Answer 1

1

Change suggestions:

  1. Change structure metadata tag json to bson
type Student struct {
    ID           primitive.ObjectID   `bson:"_id,omitempty"`
    ...
    Users      []primitive.ObjectID   `bson:"users"`
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

It's not working. I did this var values = []primitive.ObjectID{ID}
@VarunRaj have you tried using single value like your example? that also failed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.