Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mongo
- import (
- "log"
- "time"
- "github.com/davixcky/AgropecuariaArcadia-Server/common"
- "github.com/globalsign/mgo"
- )
- var session *mgo.Session
- func createDBSession() {
- var err error
- session, err = mgo.DialWithInfo(&mgo.DialInfo{
- Addrs: []string{common.AppConfig.MongoDBHost},
- Username: common.AppConfig.DBUser,
- Password: common.AppConfig.DBPwd,
- Timeout: 60 * time.Second,
- })
- if err != nil {
- log.Fatalf("[createDBSession]: %s\n", err)
- }
- }
- func getSession() *mgo.Session {
- if session == nil {
- var err error
- session, err = mgo.DialWithInfo(&mgo.DialInfo{
- Addrs: []string{common.AppConfig.MongoDBHost},
- Username: common.AppConfig.DBUser,
- Password: common.AppConfig.DBPwd,
- Timeout: 60 * time.Second,
- })
- if err != nil {
- log.Fatalf("[getSession]: %s\n", err)
- }
- createDBSession()
- }
- return session
- }
- func addUserIndex() {
- log.Println("Adding indexes")
- var index []mgo.Index
- index = append(index, mgo.Index{
- Key: []string{"last_name"},
- Unique: true,
- Background: true,
- })
- index = append(index, mgo.Index{
- Key: []string{"username"},
- Unique: true,
- Background: true,
- })
- index = append(index, mgo.Index{
- Key: []string{"email"},
- Unique: true,
- Background: true,
- })
- session := getSession().Copy()
- defer session.Close()
- userC := session.DB(common.AppConfig.Database).C("users")
- ensureIndexes(index, userC)
- }
- func ensureIndexes(indexes []mgo.Index, col *mgo.Collection) {
- var err error
- for _, i := range indexes {
- err = col.EnsureIndex(i)
- if err != nil {
- log.Fatalf("[addIndexes]: %s\n", err)
- }
- }
- }
- func InitMongo() {
- createDBSession()
- addUserIndex()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement