doutongfu9484 2015-10-08 20:40
浏览 76
已采纳

使用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条回答 默认 最新

  • dongshan6870 2015-10-09 02:05
    关注

    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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?