无法检索“_id”使用mgo和golang的价值 [英] Cannot retrieve "_id" value using mgo with golang
本文介绍了无法检索“_id”使用mgo和golang的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的结构定义:
type Article结构{
,我使用了
Id bson.ObjectId`json:id bson:_ id,omitempty`
标题字符串`json:title`
作者字符串`json:author`
日期字符串`json:date`
标签字符串`json:标签``
内容字符串`json:content`
状态字符串`json:status`
}
$ c
$ b这是我从数据库获取数据的方法:
func AllArticles()[] Article {$ b $ articles:= [] Article {}
err:= c_articles.Find(bson.M {})。All(& articles)
if err!= nil {
panic(err)
}
return articles
}
这是存储在数据库中的一个对象:
{_id:ObjectId(5281b83afbb7f35cb62d0834),
title:Hello1,
author:DYZ,
date:20 13-11-10,
tags:abc,
content:这是另一个内容。,
status:published}
这是打印结果:
[{ObjectIdHex()Hello1 DYZ 2013-11-10 abc这是另一个内容。发布} {ObjectIdHex()Hello2 DYZ 2013-11-14 abc这是内容。已发布}]
看来我无法获得
_id
字段,它总是。问题是什么?
解决方案我发现了这个问题。
在代码中:
Id bson.ObjectId`json:idbson:_ id,omitempty`$ b $
json:
和bson之间的b
:
选项卡
而不是space
,所以问题就出现了。如果我将这行代码更改为:Id bson.ObjectId`json:idbson:_ id,omitempty `
使用一个
空格
之间json:
和bson:
,结果证明工作得很好。This is my struct definition:
type Article struct { Id bson.ObjectId `json:"id" bson:"_id,omitempty"` Title string `json:"title"` Author string `json:"author"` Date string `json:"date"` Tags string `json:"tags"` Content string `json:"content"` Status string `json:"status"` }
This is the method I get my data from database:
func AllArticles() []Article { articles := []Article{} err := c_articles.Find(bson.M{}).All(&articles) if err != nil { panic(err) } return articles }
This is one piece of object stored in database:
{ "_id" : ObjectId( "5281b83afbb7f35cb62d0834" ), "title" : "Hello1", "author" : "DYZ", "date" : "2013-11-10", "tags" : "abc", "content" : "This is another content.", "status" : "published" }
This is the printed result:
[{ObjectIdHex("") Hello1 DYZ 2013-11-10 abc This is another content. published} {ObjectIdHex("") Hello2 DYZ 2013-11-14 abc This is the content. published}]
It seems that I can't get the real value of
_id
field, it's always""
. What's the problem?解决方案I've found the problem.
In the code:
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
between
json:
andbson:
, I used atab
instead ofspace
so the problem occurs. If I change this line of code to:Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
With one
space
betweenjson:
andbson:
, it turns out to work just fine.这篇关于无法检索“_id”使用mgo和golang的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文