Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Support primary keys in struct as Id_ instead of _id

  • Loading branch information...
commit b56fb291846e74ed2a670976111ef70dbbc37240 1 parent 17c9a48
chbug chbug authored committed
Showing with 30 additions and 1 deletion.
  1. +6 −0 mongo/bson-struct.go
  2. +6 −1 mongo/bson.go
  3. +18 −0 mongo/bson_test.go
6 mongo/bson-struct.go
View
@@ -288,6 +288,12 @@ func Marshal(val interface{}) (BSON, os.Error) {
if err != nil {
return nil, err
}
+ // MongoDB uses '_id' as the primary key, but this
+ // name is private in Go. Use 'Id_' for this purpose
+ // instead.
+ if key == "id_" {
+ key = "_id"
+ }
o.value[key] = el
}
return o, nil
7 mongo/bson.go
View
@@ -389,7 +389,6 @@ func (self *_BSONBuilder) OID(o []byte) { self.Put(&_OID{o, _Null{}}) }
func (self *_BSONBuilder) Key(key string) Builder {
bb2 := new(_BSONBuilder)
-
switch obj := self.Get().(type) {
case *_Object:
bb2.obj = obj.value
@@ -443,6 +442,12 @@ func Parse(buf *bytes.Buffer, builder Builder) (err os.Error) {
for kind != EOOKind {
name := readCString(buf)
+ // MongoDB uses '_id' as the primary key, but this
+ // name is private in Go. Use 'Id_' for this purpose
+ // instead.
+ if name == "_id" {
+ name = "id_"
+ }
b2 := builder.Key(name)
switch kind {
18 mongo/bson_test.go
View
@@ -30,6 +30,11 @@ type ExampleStruct struct {
Fifth OtherStruct
}
+type ExampleWithId struct {
+ Id_ string
+ Other string
+}
+
var b []byte = []byte{92, 0, 0, 0, 1, 115, 101, 99, 111, 110, 100, 0, 0, 0, 0, 0, 0, 0, 0, 64, 3, 102, 105, 102, 116, 104, 0, 23, 0, 0, 0, 2, 118, 0, 2, 0, 0, 0, 101, 0, 2, 102, 0, 2, 0, 0, 0, 105, 0, 0, 3, 102, 111, 117, 114, 116, 104, 0, 5, 0, 0, 0, 0, 2, 116, 104, 105, 114, 100, 0, 6, 0, 0, 0, 116, 104, 114, 101, 101, 0, 16, 102, 105, 114, 115, 116, 0, 1, 0, 0, 0, 0}
func TestSerializeAndDeserialize(t *testing.T) {
@@ -54,6 +59,19 @@ func TestUnmarshal(t *testing.T) {
assertTrue(es.Fifth.F == "i" && es.Fifth.V == "e", "unmarshal struct", t)
}
+func TestIdHandling(t *testing.T) {
+ ei := ExampleWithId{Id_:"fooid", Other: "bar"}
+ // verify Id_ gets turned into _id
+ parsed, err := Marshal(ei)
+ assertTrue(err == nil, "cannot marshal", t)
+ assertTrue(parsed.Get("_id").String() == "fooid", "no _id", t)
+ // ...and vice-versa
+ var back ExampleWithId
+ err = Unmarshal(parsed.Bytes(), &back)
+ assertTrue(err == nil, "cannot unmarshal", t)
+ assertTrue(back.Id_ == "fooid", "no _id back", t)
+}
+
type ExampleStruct2 struct {
Date *time.Time
}
Please sign in to comment.
Something went wrong with that request. Please try again.