Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mgo convert bson.objectId to string(hex) in html template

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?

like image 531
armnotstrong Avatar asked Mar 12 '15 10:03

armnotstrong


1 Answers

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>
like image 190
Gustavo Niemeyer Avatar answered Oct 18 '22 18:10

Gustavo Niemeyer