使用Mgo创建自定义ID

时间:2014-10-24 10:46:30

标签: mongodb go

我目前正在使用GoLang和MongoDB。我正在编写一个小型Web应用程序,一个更具体的博客(这就像我在尝试新语言时编写的第一个webapp)。即使我一开始遇到麻烦,一切都可以和MGO一起使用。但现在我想分别访问每个博客条目(文章将被称为条目以坚持我的模型)。我可以在url中使用ObjectID。但那太可怕了。例如:
mydomain.com/entries/543fd8940e82533995000002/
这不是用户友好的。我在互联网上做了很多研究以找到合适的解决方案,因为使用任何其他数据库引擎我只能使用id(这样会很好)。

有人可以帮我创建一个自定义(公共)ID,当我插入一个新条目并且我可以在网址中使用它时会自动增加吗?

以下是我的模型的代码:

package models

import (
    "time"

    "labix.org/v2/mgo"
    "labix.org/v2/mgo/bson"
)

type (
    Entries []Entry
    Entry   struct {
        ID      bson.ObjectId `bson:"_id,omitempty"`
        Title   string        `bson:"title"`
        Short   string        `bson:"short"`
        Content string        `bson:"content"`
        Posted  time.Time     `bson:"posted"`
    }
)

// Insert an entry to the database
func InsertEntry(database *mgo.Database, entry *Entry) error {
    entry.ID = bson.NewObjectId()
    return database.C("entries").Insert(entry)
}

// Find an entry by id
func GetEntryByID(database *mgo.Database, id string) (entry Entry, err error) {
    bid := bson.ObjectIdHex(id)
    err = database.C("entries").FindId(bid).One(&entry)
    return
}

// Retrieves all the entries
func AllEntries(database *mgo.Database) (entries Entries, err error) {
    err = database.C("entries").Find(nil).All(&entries)
    return
}

// Retrieve all the entries sorted by date.
func AllEntriesByDate(database *mgo.Database) (entries Entries, err error) {
    err = database.C("entries").Find(nil).Sort("-posted").All(&entries)
    return
}

// Counts all the entries.
func CountAllEntries(database *mgo.Database) (count int, err error) {
    count, err = database.C("entries").Find(nil).Count()
    return
}

1 个答案:

答案 0 :(得分:3)

如您所知,_id是必填字段,当您未设置时,它会自动由驱动程序填充。这是您当前的应用程序/代码中的行为。您可以在此处找到有关此类型及其生成的信息:http://docs.mongodb.org/manual/reference/object-id/

但是,您可以创建自己的_id并将值设置为对您的业务有意义的任何内容。

这就是为什么我不理解以下陈述:

  

我在互联网上进行了大量研究以找到合适的解决方案,因为使用任何其他数据库引擎我只能使用id(这样会很好)。

只要您的收藏品是唯一的,就可以使用您想要的任何值。

关于自动增量,MongoDB不提供任何自动增量字段,因此您必须自己实现它,并从您的应用程序中调用增量。

例如,您创建一个包含“序列/计数器”的新集合:(不显示shell命令)

{
  _id : "entry",
  sequence : 0
}

然后,当您想要文档的新ID时,首先要更新,使用find并使用简单的$ inc操作修改您创建的文档

var ret = db.counters.findAndModify(
          {
            query: { _id: "entry" },
            update: { $inc: { seq: 1 } },
            new: true
          }
   );

然后,您可以将返回的值用作新文档_id。

此模式记录在此处: http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/