用mgo强制执行一个类型映射 [英] Enforce a type mapping with mgo

查看:139
本文介绍了用mgo强制执行一个类型映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个_id成员不会被映射到ObjectId类型,当它的类型只从bson.ObjectId派生时:

  import (
gopkg.in/mgo.v2
gopkg.in/mgo.v2/bson


类型CustomId bson.ObjectId

type Foo struct {
ID1 CustomId`bson:_ id``破碎
ID2 bson.ObjectId //按预期映射
}


func main(){
session,_:= mgo.Dial(127.0.0.1)
coll:= session.DB(mgodemo)。C(foocoll )
$ b $ doc:= Foo {
CustomId(bson.NewObjectId()),
bson.NewObjectId(),
}

coll.sert(doc)
}

_id应该是一个 ObjectId 在Mongo中。
但事实证明, string 是被选中的:

Mongo Shell:

 > db.foocoll.findOne()
{_id:XvMn]K \\ \\ ,id2:ObjectId(58764d6e5d4be120fa0c3ab1)} // id2 is OK ...

> typeof db.foocoll.findOne()._ id
string // OOps。应该是ObjectId!

这可能是有意的,因为 bson.ObjectId 本身是从字符串。但是在这里,这对我们是不利的。



我们可以告诉mgo将_id映射到数据库中的ObjectId吗?

解决方案

使用 Setter方法 Getter 接口来控制mongo中的表示形式:

  type CustomId bson.ObjectId 

func(id * CustomId)SetBSON(raw bson.Raw)error {
var v bson.ObjectId
err:= raw.Unmarshal(& v)
* id = CustomId(v)
return err
}
func (id CustomId)GetBSON()(interface {},error){
return bson.ObjectId(id),nil
}


An _id member is not mapped to type ObjectId anymore, when its type is only derived from bson.ObjectId:

import (
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type CustomId bson.ObjectId

type Foo struct {
    ID1    CustomId `bson:"_id"` // broken
    ID2    bson.ObjectId         // mapped as expected
}


func main() {
    session, _ := mgo.Dial("127.0.0.1")
    coll := session.DB("mgodemo").C("foocoll")

    doc := Foo{
        CustomId(bson.NewObjectId()),
        bson.NewObjectId(),
    }

    coll.Insert(doc)
}

The _id should have been an ObjectId in Mongo. But it turns out that string was choosen:

Mongo Shell:

> db.foocoll.findOne()
{ "_id" : "XvMn]K� �\f:�", "id2" : ObjectId("58764d6e5d4be120fa0c3ab1") }  // id2 is OK ...

> typeof db.foocoll.findOne()._id
string  // OOps. Should be ObjectId !

This may be intended, since bson.ObjectId itself is derived from string. But here, it's bad for us.

Can we tell mgo to map the _id to ObjectId in the Database ?

解决方案

Use the Setter and Getter interfaces to control the representation in mongo:

type CustomId bson.ObjectId

func (id *CustomId) SetBSON(raw bson.Raw) error {
   var v bson.ObjectId
   err := raw.Unmarshal(&v)
   *id = CustomId(v)
   return err
}
func (id CustomId) GetBSON() (interface{}, error) {
   return bson.ObjectId(id), nil
}

这篇关于用mgo强制执行一个类型映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆