如何编写插入golang代码?

时间:2016-05-21 08:20:31

标签: go mgo

  

这是我的json文件,我想使用golang插入数据   这种json格式的mgo

[{
    "_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
        }
    ]
}]
  

现在,这是我的go文件,我试图插入数据   golang和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)
}
  

但它根本不起作用请帮帮我

2 个答案:

答案 0 :(得分:2)

这有很多错误。

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. 会话

  2. 所有模型的单独集合

  3. 我已将Userinfo的用户和销售字段更改为[]字符串,因为每个独立可编辑且可查询的模型都应具有自己的集合。而不是整个对象保存了id引用,因此您可以通过ObjectId查询用户。

    1. Userinfo应为大写

答案 1 :(得分:1)

您的语法在几个地方都已关闭。但是代码很乱,所以我会把它分开:

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()}

关于销售和用户的创建,这不是创建切片和结构的正确方法。 Golang中T类型结构的实例化是T{}。您可以以相同的方式创建切片。因此,salesusers变为

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

然后,你应该看看mgo的文档。创建ObjectId的方法是bson.NewObjectId()。现在,进行所有修改:

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"
}
*/