dphphvs496524 2015-03-12 10:42
浏览 279
已采纳

mgo在HTML模板中将bson.objectId转换为string(hex)

I know this problem maybe duplicate to this one. But it hasn't get a satisfied answer till now. And I really want to draw some attention to get a solution as soon as possible. So I beg you not to close this issue unless you have the solution and answered it in the previous one :-)

I will describe the issue for convince:

I have a data structure that was stored in mongodb, as known, the _id of mongodb is a bson.ObjectId type, I could retrieve that with sort of like this:

type Data struct {
    Id bson.ObjectId `bson:"_id,omitempty"`
    Content string `bson:"content"`
}

Then I got a slice of Data by finding with specific query condition, and use that slice in http/template to render for front-end view. In order to manipulate every item in the slice, I want to use the Id field, but When using that with:

{{range $key, $value := .DataSlice}}
  <td>{{$value.Id}}</td>
{{end}}

That Only gives a sort of string like ObjectIdHex("550146d1b51bc1c208d1924d") instead of 550146d1b51bc1c208d1924d which is nice and easy to use.

In the duplicate issue. The op have said that He found a way to resolve this by "adding a Id_String" to the original data structure. But I really don't know how to do this? Is that mean assign it after retrieval ? Since I use a slice to store the data retrieved, And data in a slice couldn't be changed easily. It will be more complex to do that than do the job in the front-end using jquery. But doing that just depress me with my beloved Go :-(.

So is There a better way to do that?

  • 写回答

2条回答 默认 最新

  • dqlk31541 2015-03-12 13:54
    关注

    The bson.ObjectId type offers a Hex method that will return the hex representation you are looking for, and the template package allows one to call arbitrary methods on values you have at hand, so there's no need to store that value in duplicity anywhere else as a string.

    This would work, for example:

    <td>{{$value.Id.Hex}}</td>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab