Duplicate Id in mongodb with go

huangapple go评论77阅读模式
英文:

Duplicate Id in mongodb with go

问题

我正在尝试使用Go和Mongodb编写一个简单的Web应用程序。
我已经创建了一个简化的Model / Controller设置。
我可以使用POST和URL“/user”以及数据“{“pseudo”:“bobby1”}”创建新用户。用户已创建。然而,在查看Mongodb shell时,我得到了以下结果:

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

“id”字段是来自我的结构体,而“_id”字段是来自Mongodb的字段。从查看不同的示例代码来看,我似乎可以使用Mongodb的那个字段,但我找不到如何做到这一点... ><
由于“id”只由我使用,我无法通过ID查找用户,因为我没有那个...
此外,当我执行GET /user时,它返回用户的完整列表,我只得到:

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

而不是“真正的”Mongodb Id...

谢谢,

以下是代码:

model/user.go

const userCollection = "user"

// 获取我们的集合
var C *mgo.Collection = database.GetCollection(userCollection)

// User 表示数据库中用户的字段
type User struct {
	Id     bson.ObjectId `json:"id" bson:"_id,omitempty"`
	Pseudo string        `json:"pseudo" bson:"pseudo"`
}

// 返回数据库中的所有用户
func UserFindAll() []User {
	var users []User
	err := C.Find(bson.M{}).All(&users)
	if err != nil {
		panic(err)
	}
	return users
}

// UserFindId 根据对应的ID返回数据库中的用户
func UserFindId(id string) User {
	if !bson.IsObjectIdHex(id) {
		s := fmt.Sprintf("给定的ID %s 无效。", 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 在数据库中创建一个新用户
func UserCreate(u *User) {
	u.Id = bson.NewObjectId()
	err := C.Insert(u)
	if err != nil {
		panic(err)
	}
}

controller/user.go

// GetAll 返回所有用户
func (us *UserController) GetAll(w http.ResponseWriter, request *http.Request) {
	users := model.UserFindAll()
	bu, err := json.Marshal(users)
	if err != nil {
		fmt.Printf("在编组用户结构时出错:%v\n", err)
		w.Write([]byte("编组错误"))
		w.WriteHeader(404)
		return
	}

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

// Get 根据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("在编组用户结构时出错:%v\n", err)
		w.Write([]byte("编组错误"))
		w.WriteHeader(404)
		return
	}

	w.Header().Set("Content-type", "application/json")
	w.WriteHeader(200)
	fmt.Fprintf(w, "%s\n", 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("在编组用户结构时出错:%v\n", err)
		w.WriteHeader(404)
		return
	}

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

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:

{ &quot;_id&quot; : ObjectId(&quot;5616d1ea56ca4dbc03bb83bc&quot;), &quot;id&quot; : ObjectId(&quot;5616d1ea5213c64824000001&quot;), &quot;pseudo&quot; : &quot;bobby2&quot;}

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:

{&quot;id&quot;:&quot;5616d1ea5213c64824000001&quot;,&quot;pseudo&quot;:&quot;bobby2&quot;

Not the "real" Mongodb Id...

Thanks,

Here's the code:

model/user.go

const userCollection = &quot;user&quot;

// 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:&quot;id&quot;i bson:&quot;_id,omitempty&quot;`
	Pseudo string        `json:&quot;pseudo&quot; bson:&quot;pseudo&quot;`
}

// it will return every users in the db
func UserFindAll() []User {
	var users []User
	err := C.Find(bson.M{}).All(&amp;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(&quot;Id given %s is not valid.&quot;, id)
		panic(errors.New(s))
	}
	oid := bson.ObjectIdHex(id)
	u := User{}
	if err := C.FindId(oid).One(&amp;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:     &quot;987654321&quot;,
	//		Pseudo: &quot;nikko&quot;,
	//	}
	users := model.UserFindAll()
	bu, err := json.Marshal(users)
	if err != nil {
		fmt.Printf(&quot;[-] Error while marshaling user struct : %v\n&quot;, err)
		w.Write([]byte(&quot;Error Marshaling&quot;))
		w.WriteHeader(404)
		return
	}

	w.Header().Set(&quot;Content-type&quot;, &quot;application/json&quot;)
	w.WriteHeader(200)
	fmt.Fprintf(w, &quot;%s\n&quot;, 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[&quot;id&quot;]
	u := model.UserFindId(ps)
	bu, err := json.Marshal(u)
	if err != nil {
		fmt.Printf(&quot;[-] Error while marshaling user struct : %v\n&quot;, err)
		w.Write([]byte(&quot;Error Marshaling&quot;))
		w.WriteHeader(404)
		return
	}

	w.Header().Set(&quot;Content-type&quot;, &quot;application/json&quot;)
	w.WriteHeader(200)
	fmt.Fprintf(w, &quot;%s\n&quot;, bu)
}

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

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

	w.Header().Set(&quot;Content-type&quot;, &quot;application/json&quot;)
	w.WriteHeader(201)
	fmt.Fprintf(w, &quot;%s\n&quot;, bu)
}

答案1

得分: 1

看起来你的结构标签中有一个多余的字符:

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

json:"id" 后面不应该有 i。应该是这样的:

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

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

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

That i should not exist after json:&quot;id&quot;. It should be:

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

huangapple
  • 本文由 发表于 2015年10月9日 04:40:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/33025572.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定