mgo中的关系

huangapple go评论65阅读模式
英文:

Relationships in mgo

问题

我用golang和mgo编写了一些简单的程序。我的问题是如何在mgo中正确处理关系。

第一种方法:

type User struct {
    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    Username string          `json:"username" bson:"username"`
    Email    string          `json:"email" bson:"email"`
    Password string          `json:"password" bson:"password"`
    Friends  []User          `json:"friends" bson:"friends"`
}

"Friends"是一个User类型的切片。我可以使用$push将一个User的指针添加到其中,这样就可以正常工作。问题是,我只想存储对用户的引用,而不是嵌套它。

第二种方法:

type User struct {
    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    Username string          `json:"username" bson:"username"`
    Email    string          `json:"email" bson:"email"`
    Password string          `json:"password" bson:"password"`
    Friends  []bson.ObjectId `json:"friends" bson:"friends"`
}

这样可以得到我想要的输出,但是现在从结构体中无法看到哪些嵌套结构体被引用了。mgo是否提供了处理这个问题的机制?

英文:

I've written some simple program with golang and mgo. My question is how to properly to relationships in mgo.

1st Approach:

type User struct {
	Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
	Username string          `json:"username" bson:"username"`
	Email    string          `json:"email" bson:"email"`
	Password string          `json:"password" bson:"password"`
	Friends  []User          `json:"friends" bson:"friends"`
}

"Friends" is a slice of Users. I can $push a pointer to a User and it just works fine. The thing is that I only want to store a reference to the user and not nesting it:

2nd Approach:

type User struct {
	Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
	Username string          `json:"username" bson:"username"`
	Email    string          `json:"email" bson:"email"`
	Password string          `json:"password" bson:"password"`
	Friends  []bson.ObjectId `json:"friends" bson:"friends"`
}

This gives me the output I want - but now it's not visible from the struct which nested structs are referenced. Does mgo provide some mechanism to deal with this?

答案1

得分: 7

mgo是一个数据库驱动库,而不是ORM(对象关系映射)。我会按照第二个示例中的方式使用ids数组(小写字母开头,未导出),并创建一个Friends()方法,该方法通过这些ids查询数据库,并返回一个[]User。

英文:

mgo is a db driver library and not an ORM..
What I'd do is have the ids array as in the 2nd example (unexported, with lowercase) and have a Friends() method which queries the db by those ids and return a []User

huangapple
  • 本文由 发表于 2014年12月27日 00:28:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/27659487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定