-
-
Save BradErz/a947198bddf537532190fdb5ea015af3 to your computer and use it in GitHub Desktop.
mongodb connection issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// GetDatabase connects and returns a new mongodb database (service name is used by default but this can | |
// be overridden by MongoClientConfig.MongoDatabase) | |
func GetDatabase(opts ...Option) (*mongo.Database, error) { | |
c, err := getConfig(opts...) | |
if err != nil { | |
return nil, err | |
} | |
client, err := GetClient(c.conf) | |
if err != nil { | |
return nil, err | |
} | |
return client.Database(c.conf.MongoDBDatabase), nil | |
} | |
func GetClient(conf *Config) (*mongo.Client, error) { | |
if conf == nil { | |
return nil, errors.New("conf cannot be empty") | |
} | |
opts := options.Client() | |
opts.ApplyURI(config.MongoDBUri) | |
log.Println("attempting to connect to mongo") | |
ctx, cancel := context.WithTimeout(context.Background(), conf.MongoDBConnectTimeout) | |
defer cancel() | |
client, err := mongo.Connect(ctx, opts) | |
if err != nil { | |
log.Println("connection failed") | |
return nil, err | |
} | |
log.Println("successfully connected to mongo") | |
// Ping to make sure connection is usable | |
log.Println("attempting ping") | |
ctx, cancel = context.WithTimeout(context.Background(), conf.MongoDBConnectTimeout) | |
defer cancel() | |
if err := client.Ping(ctx, nil); err != nil { | |
log.Println("ping failed") | |
return nil, err | |
} | |
return client, err | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (s service) GetAllMMs(ctx context.Context, filter map[string]interface{}) ([]matchmaking.MM, error) { | |
var mms []matchmaking.MM | |
cursor, err := s.db.Collection(mmCol).Find(ctx, filter) | |
if err != nil { | |
return mms, err | |
} | |
defer cursor.Close(ctx) | |
for cursor.Next(ctx) { | |
var mm matchmaking.MM | |
if err := cursor.Decode(&mm); err != nil { | |
s.log.WithError(err).Error("could not unmarshal returned document into a matchmaking") | |
return mms, err | |
} | |
mms = append(mms, mm) | |
} | |
if len(mms) == 0 { | |
return mms, util.NewNotFoundError(filter) | |
} | |
return mms, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment