dongliu5475 2016-05-21 08:20
浏览 28
已采纳

如何编写插入golang代码?

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

  • 写回答

2条回答 默认 最新

  • dongyong5255 2016-05-21 10:41
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程