-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.go
41 lines (33 loc) · 1.02 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
package utils
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
// NewMongoConnection connect to mongodb server, returning a reusable mongo connection.
func NewMongoConnection(ctx context.Context, uri string) (client *mongo.Client, err error) {
clientOpt := options.
Client().
ApplyURI(uri).
SetWriteConcern(writeconcern.New(writeconcern.WMajority())).
// SetReadConcern(readconcern.Snapshot()).
SetReadConcern(readconcern.Majority()).
SetReadPreference(readpref.Primary())
if client, err = mongo.NewClient(clientOpt); err != nil {
return
}
if err = client.Connect(ctx); err != nil {
return
}
if err = client.Ping(ctx, readpref.Primary()); err != nil {
return
}
return client, nil
}
// NotFound is shortcut for Error no documents in mongodb
func NotFound(err error) bool {
return err == mongo.ErrNoDocuments
}