dsjj15012 2014-10-24 10:46
浏览 152
已采纳

使用Mgo创建自定义ID

I'm currently starting with GoLang and MongoDB.I'm writing a small web application, a blog to be more specific (which is like the first webapp I write when I try new languages). Everything works fine with MGO even if I had some troubles at first. But now I'd like to access each blog entry (articles will be referred as entries to stick with my models) separately. I could use the ObjectID in the url. But that's damn ugly. For example :
mydomain.com/entries/543fd8940e82533995000002/
That's not user friendly. I did a lot of research on the internet to find a suitable solution, because using any other database engine I could just use the id (and that would be fine).

Could someone help me with the creation of a custom (public) id which would auto-increment when I insert a new entry and that I could use in the url ?

Here is the code of my model for now :

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条回答 默认 最新

  • duai1683 2014-10-24 11:04
    关注

    As you know the _id is a mandatory field, that is automatically fill by the driver when you do not set it. This is the behavior that you have in your current application/code. You can find information about this type and its generation here: http://docs.mongodb.org/manual/reference/object-id/

    However, you can create your own _id and set the value to anything that makes sense for your business.

    This is why I am do not understand the following statement:

    I did a lot of research on the internet to find a suitable solution, because using any other database engine I could just use the id (and that would be fine).

    You can use any value you want as soon as it is unique for your collection.

    About the auto-increment, MongoDB does not provide any auto increment field, so you have to implement it yourself, and call the increment from your application.

    For example you create a new collection that contains your "sequences/counters": (showing shell commands not go)

    {
      _id : "entry",
      sequence : 0
    }
    

    Then when you want an new id for your document you have first to update, with a findand modify the document you have created with a simple $inc operation

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

    You can then use the returned value into you new document as an _id.

    This pattern is documented here: http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。
  • ¥15 SQL Server analysis services 服务安装失败