Search code examples
gomgo

Updating certain user fields


Requests to my API contain an ID (required) and optional others fields such as name, email and username.

{
    "id" : "12345",
    "name" : "Bob",
    "email" : "[email protected]"
}

After binding the request to a struct user if there isn't a user with the ID in my database I add them to it using:

user.App_id = appId
user.Created_at = (*tools.Timestamp)(&now)
user.Updated_at = (*tools.Timestamp)(&now)
_ = C.Database.C("users").Insert(&user);

but if there is a user I only want to update the fields that the request object includes but I'm not sure how to write the query.

My user struct uses pointers so that I can check for nil values

type user struct {
    Id      *string    `bson:"id" json:"id"`
    Name    *string    `bson:"name" json:"name"`
    ...
}

An update query that i've used elsewhere in my app looks like this:

err := collection("users").Update(bson.M{"id" : "user.Id"},bson.M{"$set": bson.M{"???":"???"}})

but I'm not sure how to construct the latter part of the query under these circumstances.

Note: I'm not using MongoDB's _id


Solution

  • I believe you should be able to accomplish this with just

    err := collection("users").Update(bson.M{"id" : user.Id},bson.M{"$set": &user})