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条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算