-
Notifications
You must be signed in to change notification settings - Fork 7
/
mongo.go
73 lines (65 loc) · 1.39 KB
/
mongo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package deps
import (
"flag"
"gopkg.in/mgo.v2"
)
var (
// MongoURL config uri
MongoURL string
// MongoName db name
MongoName string
ShouldSeed = flag.Bool("should-seed", false, "determines whether we seed the initial categories and admin user to bootstrap the site")
)
func IgniteMongoDB(container Deps) (Deps, error) {
session, err := mgo.Dial(MongoURL)
if err != nil {
log.Error(err)
log.Info(MongoURL)
return container, err
}
db := session.DB(MongoName)
collections, err := db.CollectionNames()
if err != nil {
return container, err
}
seed := true
for _, v := range collections {
if v == "users" {
seed = false
break
}
}
if seed {
ShouldSeed = &seed
}
// Ensure indexes
db.C("users").EnsureIndex(
mgo.Index{
Key: []string{"email"},
Unique: true,
Background: true,
},
)
db.C("users").EnsureIndex(
mgo.Index{
Key: []string{"username"},
Unique: true,
Background: true,
},
)
search := mgo.Index{
Key: []string{"$text:title", "$text:content"},
Weights: map[string]int{
"title": 3,
"content": 1,
},
DefaultLanguage: "spanish",
Background: true, // See notes.
}
db.C("posts").EnsureIndex(search)
// See https://godoc.org/gopkg.in/mgo.v2#Session.SetMode
//session.SetMode(mgo.Monotonic, true)
container.DatabaseSessionProvider = session
container.DatabaseProvider = db
return container, nil
}