저는 현재 GoLang과 MongoDB로 시작하고 있습니다. 좀 더 구체적 인 블로그 인 작은 웹 응용 프로그램을 작성하고 있습니다. (새로운 언어를 사용해 보았을 때 처음 작성한 webapp와 같습니다). 처음에는 몇 가지 문제가 있더라도 MGO로 모든 것이 잘 작동합니다. 하지만 이제는 각 블로그 항목에 액세스하고 싶습니다. 기사는 별도로 내 모델과 연결되는 항목으로 참조됩니다. URL에 ObjectID를 사용할 수 있습니다. 그러나 그것은 추한 추한 것이다. 예 :
mydomain.com/entries/543fd8940e82533995000002/
사용자에게 친숙하지 않습니다. 나는 적절한 ID를 사용할 수있는 다른 데이터베이스 엔진을 사용하기 때문에 적절한 솔루션을 찾기 위해 인터넷에서 많은 연구를했다.Mgo로 사용자 정의 ID 만들기
새 항목을 삽입 할 때 자동 증가하는 사용자 정의 (공개) ID 생성에 도움을 줄 수 있고 URL에 사용할 수 있습니까? 여기
지금은 내 모델의 코드입니다 :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
}
당신은 객체가 추가로 증가 필드를 저장하는 분리 수거를 유지해야합니다. Mongo 측에서 전적으로 이것을 처리 할 수있는 Javascript로 함수를 작성하는 한 그것은 그렇게 나쁘지 않습니다. 그렇지 않으면 Go에서 먼저 검색하고 문서를 증가시키기 전에 증분 값을 사용해야합니다. –