使用go在mongodb中复制ID

I'm trying to code a simple web app in Go using Mongodb. I've created a minimalistic simple Model / Controller setup. I can create new user using POST with url "/user" with data such as '{"pseudo": "bobby1"}'. The user is created. However, when looking inside Mongodb shell, I get:

{ "_id" : ObjectId("5616d1ea56ca4dbc03bb83bc"), "id" : ObjectId("5616d1ea5213c64824000001"), "pseudo" : "bobby2"}

The "id" field is the one coming from my struct and the "_id" field is the one from Mongodb. From looking at different sample code, it looked like I could use myself the one from Mongodb but I can't find how to do it.. >< Since the "id" is only used by me, I can't find user by their ID since I do not have that one... More over, when I do a GET /user, it returns the full list of user, and I only get:

{"id":"5616d1ea5213c64824000001","pseudo":"bobby2"

Not the "real" Mongodb Id...

Thanks,

Here's the code:

model/user.go

const userCollection = "user"

// Get our collection
var C *mgo.Collection = database.GetCollection(userCollection)

// User represents the fields of a user in db
type User struct {
    Id     bson.ObjectId `json:"id"i bson:"_id,omitempty"`
    Pseudo string        `json:"pseudo" bson:"pseudo"`
}

// it will return every users in the db
func UserFindAll() []User {
    var users []User
    err := C.Find(bson.M{}).All(&users)
    if err != nil {
        panic(err)
    }
    return users
}

// UserFIndId return the user in the db with
// corresponding ID
func UserFindId(id string) User {
    if !bson.IsObjectIdHex(id) {
        s := fmt.Sprintf("Id given %s is not valid.", id)
        panic(errors.New(s))
    }
    oid := bson.ObjectIdHex(id)
    u := User{}
    if err := C.FindId(oid).One(&u); err != nil {
        panic(err)
    }
    return u
}

// UserCreate create a new user on the db
func UserCreate(u *User) {
    u.Id = bson.NewObjectId()
    err := C.Insert(u)
    if err != nil {
        panic(err)
    }
}

controller/user.go

/ GetAll returns all users
func (us *UserController) GetAll(w http.ResponseWriter, request *http.Request) {
    //  u := model.User{
    //      ID:     "987654321",
    //      Pseudo: "nikko",
    //  }
    users := model.UserFindAll()
    bu, err := json.Marshal(users)
    if err != nil {
        fmt.Printf("[-] Error while marshaling user struct : %v
", err)
        w.Write([]byte("Error Marshaling"))
        w.WriteHeader(404)
        return
    }

    w.Header().Set("Content-type", "application/json")
    w.WriteHeader(200)
    fmt.Fprintf(w, "%s
", bu)
}

// Get return a specific user according to Id
func (us *UserController) Get(w http.ResponseWriter, request *http.Request) {
    vars := mux.Vars(request)
    ps := vars["id"]
    u := model.UserFindId(ps)
    bu, err := json.Marshal(u)
    if err != nil {
        fmt.Printf("[-] Error while marshaling user struct : %v
", err)
        w.Write([]byte("Error Marshaling"))
        w.WriteHeader(404)
        return
    }

    w.Header().Set("Content-type", "application/json")
    w.WriteHeader(200)
    fmt.Fprintf(w, "%s
", bu)
}

func (us *UserController) Post(w http.ResponseWriter, r *http.Request) {
    u := model.User{}
    json.NewDecoder(r.Body).Decode(&u)
    model.UserCreate(&u)
    bu, err := json.Marshal(u)

    if err != nil {
        fmt.Printf("[-] Error PUT user struct : %v
", err)
        w.WriteHeader(404)
        return
    }

    w.Header().Set("Content-type", "application/json")
    w.WriteHeader(201)
    fmt.Fprintf(w, "%s
", bu)
}

1个回答



看起来像您的struct标记中有流浪字符:</ p>

  type User  struct {
Id bson.ObjectIdjson:“ id” i bson:“ _ id,omitempty”
伪字符串json:“ pseudo” bson:“ pseudo”
}
</ code> </ pre>

i </ code>在 json:“ id” </ code>之后不应该存在。 它应该是:</ p>

  type用户结构{
ID bson.ObjectIdjson:“ id” bson:“ _ id,omitempty”
伪字符串json:“ 伪” bson:“伪”
}
</ code> </ pre>
</ div>

展开原文

原文

Looks like you have a stray character in your struct tags:

type User struct {
    Id     bson.ObjectId `json:"id"i bson:"_id,omitempty"`
    Pseudo string        `json:"pseudo" bson:"pseudo"`
}

That i should not exist after json:"id". It should be:

type User struct {
    Id     bson.ObjectId `json:"id" bson:"_id,omitempty"`
    Pseudo string        `json:"pseudo" bson:"pseudo"`
}

duanbairan4235
duanbairan4235 我的天啊。 我会继续打我的头,并把这个东西重新编码一千遍,以示惩罚。……谢谢;)
接近 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐