我目前開始使用 GoLang 和 MongoDB。我正在編寫一個(gè)小型 Web 應(yīng)用程序,一個(gè)更具體的博客(就像我嘗試新語言時(shí)編寫的第一個(gè) Web 應(yīng)用程序)。即使一開始我遇到了一些麻煩,MGO 也一切正常。但現(xiàn)在我想分別訪問每個(gè)博客條目(文章將被稱為與我的模型保持一致的條目)。我可以在 url 中使用 ObjectID。但這該死的丑陋。例如:mydomain.com/entries/543fd8940e82533995000002/這不是用戶友好的。我在互聯(lián)網(wǎng)上進(jìn)行了大量研究以找到合適的解決方案,因?yàn)槭褂萌魏纹渌麛?shù)據(jù)庫引擎我都可以只使用 id(這樣就可以了)。有人可以幫我創(chuàng)建一個(gè)自定義(公共)id,當(dāng)我插入一個(gè)新條目時(shí)它會(huì)自動(dòng)增加并且我可以在 url 中使用它?這是我現(xiàn)在模型的代碼:package modelsimport ( "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 databasefunc InsertEntry(database *mgo.Database, entry *Entry) error { entry.ID = bson.NewObjectId() return database.C("entries").Insert(entry)}// Find an entry by idfunc 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 entriesfunc 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}
使用 Mgo 創(chuàng)建自定義 ID
慕桂英3389331
2021-08-23 17:30:03