0

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

{
    "id" : "12345",
    "name" : "Bob",
    "email" : "test@example.com"
}

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

tommyd456
  • 10,443
  • 26
  • 89
  • 163
  • How about including the import for your db package? Pretty much required to ask this question. – evanmcdonnal Sep 09 '15 at 16:23
  • What do you mean by import? – tommyd456 Sep 09 '15 at 16:25
  • You probably have `import "gopkg.in/mgo.v2"` at the top of your file but how should I know that? Maybe you're using `FictionalMongoDriver` instead. Hard to provide a decent answer when I'm speculating about what library it is you're calling. – evanmcdonnal Sep 09 '15 at 16:26
  • I was hoping the mgo tag at the bottom might help? – tommyd456 Sep 09 '15 at 16:27
  • I didn't realize that tag as specifically for the Go mgo driver... I still think it would be smart to include in your question. It's pretty simple to preface your code snippet with relevant imports. – evanmcdonnal Sep 09 '15 at 16:38
  • No worries - but any help with the actual question would be much appreciated – tommyd456 Sep 09 '15 at 16:39

1 Answers1

0

I believe you should be able to accomplish this with just

err := collection("users").Update(bson.M{"id" : user.Id},bson.M{"$set": &user})
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115