英文:
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:
{ "_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\n", err)
w.Write([]byte("Error Marshaling"))
w.WriteHeader(404)
return
}
w.Header().Set("Content-type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s\n", 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\n", err)
w.Write([]byte("Error Marshaling"))
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("[-] Error PUT user struct : %v\n", err)
w.WriteHeader(404)
return
}
w.Header().Set("Content-type", "application/json")
w.WriteHeader(201)
fmt.Fprintf(w, "%s\n", 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:"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"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论