Add ability to supply Mongo connection uri

This commit is contained in:
Kalissaac
2020-12-01 14:18:33 -08:00
parent 0db60a3462
commit 1d00ff6dd8
3 changed files with 47 additions and 19 deletions

View File

@@ -48,11 +48,25 @@ store := mongodb.New(mongodb.Config{
Collection: "fiber_storage",
Reset: false,
})
// Initialize custom config using connection string
store := mongodb.New(mongodb.Config{
Connection: "mongodb://user:password@127.0.0.1:27017",
Database: "fiber",
Collection: "fiber_storage",
Reset: false,
})
```
### Config
```go
type Config struct {
// Connection string to use for DB. Will override all other authentication values if used
//
// Optional. Default is ""
Connection string
// Whether the DB is hosted on MongoDB Atlas
//
// Optional. Default is false
@@ -98,6 +112,7 @@ type Config struct {
### Default Config
```go
var ConfigDefault = Config{
Connection: "",
Atlas: false,
Host: "127.0.0.1",
Port: 27017,

View File

@@ -2,6 +2,11 @@ package mongodb
// Config defines the config for storage.
type Config struct {
// Connection string to use for DB. Will override all other authentication values if used
//
// Optional. Default is ""
Connection string
// Whether the DB is hosted on MongoDB Atlas
//
// Optional. Default is false
@@ -45,6 +50,7 @@ type Config struct {
// ConfigDefault is the default config
var ConfigDefault = Config{
Connection: "",
Atlas: false,
Host: "127.0.0.1",
Port: 27017,

View File

@@ -33,7 +33,13 @@ func New(config ...Config) *Storage {
cfg := configDefault(config...)
// Create data source name
var dsn = "mongodb"
var dsn string
// Check if user supplied connection string
if cfg.Connection != "" {
dsn = cfg.Connection
} else {
dsn = "mongodb"
if cfg.Atlas {
dsn += "+srv://"
} else {
@@ -54,6 +60,7 @@ func New(config ...Config) *Storage {
} else {
dsn += fmt.Sprintf("%s:%d", url.QueryEscape(cfg.Host), cfg.Port)
}
}
// Set mongo options
opt := options.Client()