-1

Here Is my json file and i want to insert the data using golang and mgo in this json format

[{
    "_id" : ObjectId("57307906f051147d5317984e"),
    "dateAdded" : " 20015-11-10 23:00:00 +0000 UTC"
    "firstName" : "chetan",
    "lastName" : "kumar",
    "age" : 23,

    "user" : [
        {
            "userid" : ObjectId("57307906f051147d5317984a"),
            "firstName" : "chetan",
            "lastName" : "kumar",
            "age" : 23
        },
        {
            "userid" : ObjectId("57307906f051147d5317984b"),
            "firstName" : "nepolean",
            "lastName" : "dang",
            "age" : 26
        },
        {
            "userid" : ObjectId("57307906f051147d5317984c"),
            "firstName" : "Raj",
            "lastname" : "kumar",
            "age" : 26
        }
    ],
    "sales" : [
        {
            "salesid" : ObjectId("57307906f051147d5317984d"),
            "firstName" : "ashu",
            "lastName" : "jha",
            "age" : 27
        }
    ]
}]

Now ,here is my go file which i was trying to insert data through golang and mgo

package main

import(
    "fmt"
    "time"
    "net/http"
    "github.com/gorilla/mux"
        "gopkg.in/mgo.v2"
        "gopkg.in/mgo.v2/bson"
)
type userinfo struct{

    ID          bson.ObjectId   `json:"_id" bson:"_id"`
        USER        []User      `json:"user" bson:"user"`
    SALES       []Sales     `json:"sales" bson:"sales"`
    DATEADDED   time.Time   `json:"dateAdded" bson:"dateAdded"`
    NAME        string      `json:"name" bson:"name"`

} 
type User struct{
    USERID      bson.ObjectId   `json:"userid" bson:"userid"`
    FIRSTNAME   string      `json:"firstName" bson:"firstName"`
    LASTNAME    string      `json:"lastName" bson:"lastName"`
    AGE     int     `json:"age" bson:"age"`

}
type Sales struct{
    SALESID     bson.ObjectId   `json:"salesid" bson:"salesid"`
    FIRSTNAME   string      `json:"firstName" bson:"firstName"`
    LASTNAME    string      `json:"lastName" bson:"lastName"`
    AGE     int     `json:"age" bson:"age"`

}

func post(w http.ResponseWriter,r *http.Request){

    session,err := mgo.Dial("127.0.0.1")
    if err != nil{
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic,true)
    c:= session.DB("userdb").C("user")
    fmt.Fprintln(w,"conn")




    err = c.Insert(&userinfo{ID:new ObjectId(),NAME:"Admin",USER:{USERID:new ObjectId(), FIRSTNAME: "sam",LASTNAME : "billing",AGE : 25},SALES:{SALESID:new ObjectId(),FIRSTNAME : "joe",LASTNAME : "root",AGE : 23},DATEADDED:time.Now()})

    if err != nil {
        panic(err)
    }



}

func main(){
    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/post/",post)
    http.ListenAndServe(":8080",router)
}

but it's not work at all please help me out

Chetan Kumar
  • 328
  • 1
  • 4
  • 18

2 Answers2

2

There is so much wrong with this.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type Userinfo struct {
    ID        bson.ObjectId `bson:"_id,omitempty" json:"id"`
    USER      []string      `json:"user" bson:"user"`
    SALES     []string      `json:"sales" bson:"sales"`
    DATEADDED time.Time     `json:"dateAdded" bson:"dateAdded"`
    NAME      string        `json:"name" bson:"name"`
}

type User struct {
    ID        bson.ObjectId `bson:"_id,omitempty" json:"id"`
    FIRSTNAME string        `json:"firstName" bson:"firstName"`
    LASTNAME  string        `json:"lastName" bson:"lastName"`
    AGE       int           `json:"age" bson:"age"`
}

type Sales struct {
    ID        bson.ObjectId `bson:"_id,omitempty" json:"id"`
    FIRSTNAME string        `json:"firstName" bson:"firstName"`
    LASTNAME  string        `json:"lastName" bson:"lastName"`
    AGE       int           `json:"age" bson:"age"`
}

var session *mgo.Session

func main() {
    var err error
    session, err = mgo.Dial("127.0.0.1")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)

    fmt.Fprintln(w, "conn")

    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/post/", post)
    router.HandleFunc("/getusers/", getusers)
    http.ListenAndServe(":8080", router)

}

func post(w http.ResponseWriter, r *http.Request) {

    ms := session.Copy()
    defer ms.Close()

    cui := session.DB("userdb").C("userinfo")
    cu := session.DB("userdb").C("user")
    cs := session.DB("userdb").C("sales")

    u := User{FIRSTNAME: "sam", LASTNAME: "billing", AGE: 25}
    s := Sales{FIRSTNAME: "joe", LASTNAME: "root", AGE: 23}

    if e := cu.Insert(u); e != nil {
        log.Println(e.Error)
        w.WriteHeader(500)
        return
    }
    if e := cs.Insert(s); e != nil {
        log.Println(e.Error)
        w.WriteHeader(500)
        return
    }

    ui := new(Userinfo)
    ui.ID = bson.NewObjectId()
    ui.NAME = "admin"
    ui.USER = []string{u.Id.Hex()}
    ui.SALES = []string{s.Id.Hex()}
    ui.DATEADDED = time.Now()

    if e := cui.Insert(ui); e != nil {
        log.Println(e.Error)
        w.WriteHeader(500)
        return
    }
    w.WriteHeader(201)
}

func getusers(w http.ResponseWriter, r *http.Request) {
    ms := session.Copy()
    defer ms.Close()

    cui := session.DB("userdb").C("userinfo")
    cu := session.DB("userdb").C("user")
    cs := session.DB("userdb").C("sales")

    // Query for users of userinfo

    uadm := new(Userinfo)

    if e := cui.Find(bson.M{"name": "admin"}).One(uadm); e != nil {
        log.Println(e.Error)
    }

    for _, userid := range uadm.USER {
        tempu := new(User)
        if e := cu.Find(bson.M{"_id": bson.ObjectIdHex(userid)}).One(tempu); e != nil {
            log.Println(e.Error)
            w.WriteHeader(500)
            return
        }
        enc := json.NewEncoder(w)
        if e := enc.Encode(tempu); e != nil {
            log.Println(e.Error)
            w.WriteHeader(500)
            return
        }
    }

}
  1. The session

  2. Separate collections for all models

I've changed the user and sales fields of Userinfo into []string because every independantly editable and queryable model should have its own collection. Instead of the whole object the id reference is saved so you can query for a user by ObjectId.

  1. Userinfo should be uppercase
1

Your syntax is off, in several places. However the code is messy so I'll split it like that:

users := {USERID: new ObjectId(), FIRSTNAME: "sam",LASTNAME: "billing", AGE: 25}
sales := {SALESID: new ObjectId(),FIRSTNAME: "joe", LASTNAME: "root", AGE: 23}
info := &userinfo{ID:new ObjectId(), NAME:"Admin", USER: users, SALES: sales, DATEADDED: time.Now()}

About the creation of sales and user, this is not the right way to create a slice and a struct. Instantiation of a struct of type T in Golang is T{}. You can create slices the same way. Therefore the sales and users become

users := []User{User{USERID: new ObjectId(), FIRSTNAME: "sam",LASTNAME: "billing", AGE: 25}}
sales := []Sales{Sales{SALESID: new ObjectId(),FIRSTNAME: "joe", LASTNAME: "root", AGE: 23}}

Then, you should take a look at mgo's documentation. The way of creating an ObjectId is bson.NewObjectId(). Now, with all the modifications:

func main() {
    users := []User{User{USERID: bson.NewObjectId(), FIRSTNAME: "sam", LASTNAME: "billing", AGE: 25}}
    sales := []Sales{Sales{SALESID: bson.NewObjectId(), FIRSTNAME: "joe", LASTNAME: "root", AGE: 23}}
    info := &userinfo{ID: bson.NewObjectId(), NAME: "Admin", USER: users, SALES: sales, DATEADDED: time.Now()}
    data, _ := json.MarshalIndent(info, "", "    ")
    fmt.Println(string(data))
}

/* Prints
{
    "_id": "57402f27e13823740d742417",
    "user": [
        {
            "userid": "57402f27e13823740d742415",
            "firstName": "sam",
            "lastName": "billing",
            "age": 25
        }
    ],
    "sales": [
        {
            "salesid": "57402f27e13823740d742416",
            "firstName": "joe",
            "lastName": "root",
            "age": 23
        }
    ],
    "dateAdded": "2016-05-21T11:49:27.507636096+02:00",
    "name": "Admin"
}
*/
T. Claverie
  • 11,380
  • 1
  • 17
  • 28