Last active
June 15, 2020 07:00
-
-
Save dumebi/202042fe4abae47d0fc683771595e097 to your computer and use it in GitHub Desktop.
Trying to update a struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type User struct { | |
mogo.DocumentModel `bson:",inline" coll:"users"` | |
Username string `json:"username" binding:"required"` | |
Email string `idx:"{email},unique" json:"email" binding:"required"` | |
Password string `json:"password" binding:"required"` | |
FirstName string `json:"firstname"` | |
LastName string `json:"lastname"` | |
// CreatedAt *time.Time | |
// UpdatedAt *time.Time | |
Verified *time.Time `json:"_verified"` | |
} | |
func init() { | |
mogo.ModelRegistry.Register(User{}) | |
} | |
// Activate service removes one user | |
func (userservice Userservice) Update(user *entity.User, data map[string]interface{}) (*entity.User, error) { | |
conn := db.GetConnection() | |
defer conn.Session.Close() | |
doc := mogo.NewDoc(user).(*(entity.User)) | |
for k, v := range data { | |
fmt.Printf("%s is also %s", k, v) | |
// (doc)[k] = v | |
} | |
/* | |
the way mogo updates is | |
doc.Username = x | |
doc.Email = Y | |
but i want to be able to pass in an interface with key and value, so | |
doc.key = value | |
*/ | |
err := mogo.Save(doc) | |
if vErr, ok := err.(*mogo.ValidationError); ok { | |
return nil, vErr | |
} | |
err = mogo.Save(doc) | |
return doc, nil | |
} |
It's actually possible that mogo's Update function also allows you to pass in a map[string]interface
, but I can't tell from the docs.
yeah the docs is horrible. i was actually thinking of creating my own wrapper around it.
but abeg, i don tire
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nah, I don't know another library for doing that.
Yeah, in the main libraries, you can pass in a map into the update function (see: https://www.mongodb.com/blog/post/quick-start-golang--mongodb--how-to-update-documents;
bson.M
is an alias formap[string]interface]
), but even then I wouldn't recommend, except you really need to.If you use the actual value and the same struct you use for insertion, you retain more control about what's going in and coming out of the DB.