I'm trying to store data to MongoDB without sending null data. The Struct in question is Poll and Question. Incoming data can range from have 2 questions, to 5. So if a user only enters 2 questions I wont have a need to use the 3 other fields in Poll struct. Id rather have the fields not appear at all than send null data to the server.
package main
// Omit Empty not working
type Poll struct {
Id bson.ObjectId `bson:"_id"`
Quest0 *Question `json:"quest0,omitempty"`
Quest1 *Question `json:"quest1,omitempty"`
Quest2 *Question `json:"quest2,omitempty"`
Quest3 *Question `json:"quest3,omitempty"`
Quest4 *Question `json:"quest4,omitempty"`
Quest5 *Question `json:"quest5,omitempty"`
}
type Question struct {
Count *int `json:"count,omitempty"`
Question *string `json:"question,omitempty"`
}
type ReceivedPoll struct {
Quest0 string `db:"quest0"`
Quest1 string `db:"quest1"`
Quest2 string `db:"quest2"`
Quest3 string `db:"quest3"`
Quest4 string `db:"quest4"`
Quest5 string `db:"quest5"`
}
func main() {
fmt.Println("server running...")
router := httprouter.New()
router.POST("/api/create", api)
router.NotFound = http.FileServer(http.Dir("./public"))
log.Fatal(http.ListenAndServe(":5000", router))
}
func api(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
w.Header().Set("Content-type", "application/json")
session, err := mgo.Dial(mkey)
if err != nil {
panic(err)
}
defer session.Close()
fmt.Println("is this running?")
switch r.URL.String() {
case "/api/create":
// LOOK HERE
poll := &Poll{}
json.NewDecoder(r.Body).Decode(&poll)
poll.Id = bson.NewObjectId()
fmt.Println(*poll)
c := session.DB("abase").C("polls")
err = c.Insert(*poll)
if err != nil {
fmt.Println(err)
}
rz, _ := json.Marshal(poll.Id)
w.Write(rz)
}
}
Add the bson key used by the mgo BSON encoder. The encoder ignores the json key. See bson.Marshal documentation for the details.
type Poll struct {
Id bson.ObjectId `bson:"_id"`
Quest0 *Question `json:"quest0,omitempty" bson:"ques0:omitempty"`
...
Related
I am creating simple REST API using MongoDB and golang as a driver.
I was able to create POST request which can be found here:
terminal output.
However, when creating GET request, i always need to get it by bson _id. Would someone be able to let me know how to retrieve from json id not bson _id from golang script. If this is not possible, I would appreciate if someone let me know how to convert id to _id.
models/user.go
package models
import (
"gopkg.in/mgo.v2/bson"
)
type User struct {
Id bson.ObjectId `json:"id" bson: "_id"`
Name string `json:"name" bson: "name"`
Gender string `json:"gender" bson: "gender"`
Age int `json:"age" bson: "age"`
}
controllers/user.go file
type UserController struct {
session *mgo.Session}
func httpResponse(w http.ResponseWriter, jsonOut []byte, code int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
fmt.Fprintf(w, "%s", jsonOut)
}
func NewUserCOntroller(s *mgo.Session) *UserController {
// return the address of UserController
return &UserController{s}
}
func (uc UserController) GetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
id := p.ByName("id")
if !bson.IsObjectIdHex(id) {
w.WriteHeader(http.StatusNotFound)
}
// oid is something you use in mongo
oid := bson.ObjectIdHex(id)
u := models.User{}
if err := uc.session.DB("mongolang").C("users").FindId(oid).One(&u); err != nil {
w.WriteHeader(404)
return
}
uj, err := json.Marshal(u)
if err != nil {
fmt.Println(err)
}
httpResponse(w, uj, http.StatusOK)
}
func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// its empty for now
u := models.User{}
json.NewDecoder(r.Body).Decode(&u)
u.Id = bson.NewObjectId()
uc.session.DB("mongolang").C("users").Insert(u)
jsonOut, _ := json.Marshal(u)
httpResponse(w, jsonOut, http.StatusOK)
fmt.Println("Response:", string(jsonOut), " 201 OK")
}
main.go
package main
import (
"net/http"
"github.com/julienschmidt/httprouter"
"gopkg.in/mgo.v2"
"mongo-golang/controllers"
)
func main() {
// create new instance
r := httprouter.New()
// new session
uc := controllers.NewUserCOntroller(getSession())
r.GET("/user/:id", uc.GetUser)
r.POST("/user", uc.CreateUser)
r.DELETE("/user/:id", uc.DeleteUser)
http.ListenAndServe("localhost:9000", r)
}
func getSession() *mgo.Session {
// get session and connect with mongo
s, err := mgo.Dial("mongodb://localhost")
if err != nil {
panic(err)
}
return s
}
Would someone be able to let me know how to retrieve from json id not bson _id from golang script.
You can do that only if you save bson Id as a Hex string in the additional field in an object, but don't do that. That is unnecessary and you won't get anything.
If this is not possible, I would appreciate if someone let me know how to convert id to _id.
There are two functions that converting bson ObjectID to string and string to bson ObjectID
for id to _id, you already use that function in your code:
oid := bson.ObjectIdHex(id)
bson.ObjectIdHex() convert hex representation of objectID to bson.objectID. Hex representation is what you would see in JSON output.
After you invoke that function you get bson.ObjetID. There is a method .Hex() that can get you Hex (text/json) representation of that object.
oid := bson.ObjectIdHex(id)
json_represenation_of_bson_object_id = oid.Hex()
Also, you use the old mongo driver, a new driver written and maintained by MongoDB is what you should use:
https://github.com/mongodb/mongo-go-driver
I defined this types in GoLang:
type Comment struct {
Id int
User string
Email string
Date string
Comment string
}
type Post struct {
Id int
Special bool
Title string
Date string
Content string
Image string
Comments []Comment
}
I need to know how to modify this code:
OpenDB()
rows, _ := cn.Query(`SELECT id, date, title, special, content, image
FROM posts ORDER BY date DESC LIMIT $1
OFFSET $2`, fmt.Sprint(limit), fmt.Sprint(offset))
posts := []Post{}
for rows.Next() {
post := Post{}
e := rows.Scan(&post.Id, &post.Date, &post.Title,
&post.Special, &post.Content, &post.Image)
if e != nil {
panic(e)
}
posts = append(posts, post)
}
To allow reading comments. And also, how I can modify:
OpenDB()
_, e = cn.Exec(`INSERT INTO
posts(date, title, special, content, image)
VALUES ($1, $2, $3, $4, $5)`, date, title, special, content, image)
if e != nil {
panic(e)
}
defer CloseDB()
To allow writting an empty array of comments.
Finally I would be grateful if someone tell me how can I write single comments into an existing post.
This depends on your database schema.
If Comment has its own table you will have to loop over all comments in a Post and insert them after you have have inserted the Post. cn.Exec should return a Result which can be used to get the last inserted ID like:
result, err := cn.Exec(...)
if err != nil {
panic(err)
}
id, err := result.LastInsertId()
if err != nil {
panic(err)
}
You can now use the ID of your post as a foreign key.
If you are using a JSON column to store your comments you should define a custom type as alias for []Comment and make the type implement sql.Scanner and driver.Valuer.
type Comment struct {
Id int
User string
Email string
Date string
Comment string
}
type Comments []Comment
// Make the Comments type implement the driver.Valuer interface. This method
// simply returns the JSON-encoded representation of the struct.
func (c Comments) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Make the Comments type implement the sql.Scanner interface. This method
// simply decodes a JSON-encoded value into the struct fields.
func (c *Comments) Scan(value interface{}) error {
var b []byte
switch t := value.(type) {
case []byte:
b = t
case string:
b = string(t)
default:
return errors.New("unknown type")
}
return json.Unmarshal(b, &c)
}
I try to read and write and delete data from a Go application with the official mongodb driver for go (go.mongodb.org/mongo-driver).
Here is my struct I want to use:
Contact struct {
ID xid.ID `json:"contact_id" bson:"contact_id"`
SurName string `json:"surname" bson:"surname"`
PreName string `json:"prename" bson:"prename"`
}
// xid is https://github.com/rs/xid
I omit code to add to the collection as this is working find.
I can get a list of contacts with a specific contact_id using the following code (abbreviated):
filter := bson.D{}
cursor, err := contactCollection.Find(nil, filter)
for cur.Next(context.TODO()) {
...
}
This works and returns the documents. I thought about doing the same for delete or a matched get:
// delete - abbreviated
filter := bson.M{"contact_id": id}
result, _ := contactCollection.DeleteMany(nil, filter)
// result.DeletedCount is always 0, err is nil
if err != nil {
sendError(c, err) // helper function
return
}
c.JSON(200, gin.H{
"ok": true,
"message": fmt.Sprintf("deleted %d patients", result.DeletedCount),
}) // will be called, it is part of a webservice done with gin
// get complete
func Get(c *gin.Context) {
defer c.Done()
id := c.Param("id")
filter := bson.M{"contact_id": id}
cur, err := contactCollection.Find(nil, filter)
if err != nil {
sendError(c, err) // helper function
return
} // no error
contacts := make([]types.Contact, 0)
for cur.Next(context.TODO()) { // nothing returned
// create a value into which the single document can be decoded
var elem types.Contact
err := cur.Decode(&elem)
if err != nil {
sendError(c, err) // helper function
return
}
contacts = append(contacts, elem)
}
c.JSON(200, contacts)
}
Why does the same filter does not work on delete?
Edit: Insert code looks like this:
_, _ = contactCollection.InsertOne(context.TODO(), Contact{
ID: "abcdefg",
SurName: "Demo",
PreName: "on stackoverflow",
})
Contact.ID is of type xid.ID, which is a byte array:
type ID [rawLen]byte
So the insert code you provided where you use a string literal to specify the value for the ID field would be a compile-time error:
_, _ = contactCollection.InsertOne(context.TODO(), Contact{
ID: "abcdefg",
SurName: "Demo",
PreName: "on stackoverflow",
})
Later in your comments you clarified that the above insert code was just an example, and not how you actually do it. In your real code you unmarshal the contact (or its ID field) from a request.
xid.ID has its own unmarshaling logic, which might interpret the input data differently, and might result in an ID representing a different string value than your input. ID.UnmarshalJSON() defines how the string ID will be converted to xid.ID:
func (id *ID) UnmarshalJSON(b []byte) error {
s := string(b)
if s == "null" {
*id = nilID
return nil
}
return id.UnmarshalText(b[1 : len(b)-1])
}
As you can see, the first byte is cut off, and ID.UnmarshalText() does even more "magic" on it (check the source if you're interested).
All-in-all, to avoid such "transformations" happen in the background without your knowledge, use a simple string type for your ID, and do necessary conversions yourself wherever you need to store / transmit your ID.
For the ID Field, you should use the primitive.ObjectID provided by the bson package.
"go.mongodb.org/mongo-driver/bson/primitive"
ID primitive.ObjectID `json:"_id" bson:"_id"`
I'm learning Go and am trying to create an api endpoint that has an 'fields' parameter. When I try to scan the sqlx resulting rows it into a struct,however the fields omitted by the user are being returned as as an empty string. Is there a way that I can change the struct to reflect only the fields that the user passed? I don't think I want to use omitempty in case for example user_name is an empty string.
type User struct {
Id int `db:"id"`
UserName string `db:"user_name"`
}
func GetUsers(w http.ResponseWriter,r *http.Request,db *sqlx.DB) {
acceptedFields := map[string]bool {
"id":true,
"user_name":true,
}
var requestedFields string = "id"
if r.URL.Query().Get("fields") != ""{
requestedFields = r.URL.Query().Get("fields");
}
for _, requestedField := range strings.Split(requestedFields,",") {
if !acceptedFields[requestedField] {
http.Error(w, fmt.Sprintf("Unknown Field '%s'",requestedField), http.StatusBadRequest)
}
}
users := []User{}
err := db.Select(&users,fmt.Sprintf("SELECT %s FROM users",requestedFields));
if err != nil {
log.Fatal(err)
}
response, _ := json.Marshal(users)
fmt.Fprintf(w,string(response))
}
Resulting Endpoint Output
/users?fields=id => [{"Id":12,"UserName":""}]
Desired Endpoint Output
/users?fields=id => [{"Id":12}]
Also using sql.NullString results in this:
[{"Id":12,"UserName":{"String":"","Valid":false}}]
Thanks to mkorpriva here is a solution
type User struct {
Id int `db:"id"`
UserName *string `db:"user_name" json:",omitempty"`
}
Now I'm doing:
sess := mongodb.DB("mybase").C("mycollection")
var users []struct {
Username string `bson:"username"`
}
err = sess.Find(nil).Select(bson.M{"username": 1, "_id": 0}).All(&users)
if err != nil {
fmt.Println(err)
}
var myUsers []string
for _, user := range users{
myUsers = append(myUsers, user.Username)
}
Is there a more effective way to get slice with usernames from Find (or another search function) directly, without struct and range loop?
The result of a MongoDB find() is always a list of documents. So if you want a list of values, you have to convert it manually just as you did.
Using a custom type (derived from string)
Also note that if you would create your own type (derived from string), you could override its unmarshaling logic, and "extract" just the username from the document.
This is how it could look like:
type Username string
func (u *Username) SetBSON(raw bson.Raw) (err error) {
doc := bson.M{}
if err = raw.Unmarshal(&doc); err != nil {
return
}
*u = Username(doc["username"].(string))
return
}
And then querying the usernames into a slice:
c := mongodb.DB("mybase").C("mycollection") // Obtain collection
var uns []Username
err = c.Find(nil).Select(bson.M{"username": 1, "_id": 0}).All(&uns)
if err != nil {
fmt.Println(err)
}
fmt.Println(uns)
Note that []Username is not the same as []string, so this may or may not be sufficient to you. Should you need a user name as a value of string instead of Username when processing the result, you can simply convert a Username to string.
Using Query.Iter()
Another way to avoid the slice copying would be to call Query.Iter(), iterate over the results and extract and store the username manually, similarly how the above custom unmarshaling logic does.
This is how it could look like:
var uns []string
it := c.Find(nil).Select(bson.M{"username": 1, "_id": 0}).Iter()
defer it.Close()
for doc := (bson.M{}); it.Next(&doc); {
uns = append(uns, doc["username"].(string))
}
if err := it.Err(); err != nil {
fmt.Println(err)
}
fmt.Println(uns)
I don't see what could be more effective than a simple range loop with appends. Without all the Mongo stuff your code basically is this and that's exactly how I would do this.
package main
import (
"fmt"
)
type User struct {
Username string
}
func main() {
var users []User
users = append(users, User{"John"}, User{"Jane"}, User{"Jim"}, User{"Jean"})
fmt.Println(users)
// Interesting part starts here.
var myUsers []string
for _, user := range users {
myUsers = append(myUsers, user.Username)
}
// Interesting part ends here.
fmt.Println(myUsers)
}
https://play.golang.com/p/qCwENmemn-R