diff --git a/adapter.go b/adapter.go index 6351ff1..8c44cb9 100644 --- a/adapter.go +++ b/adapter.go @@ -157,13 +157,19 @@ func NewAdapterByDB(client *mongo.Client, config *AdapterConfig) (persist.BatchA config.Timeout = defaultTimeout } + collection := client.Database(config.DatabaseName).Collection(config.CollectionName) + a := &adapter{ client: client, - collection: client.Database(config.DatabaseName).Collection(config.CollectionName), + collection: collection, timeout: config.Timeout, filtered: config.IsFiltered, } + if err := a.prepareIndexes(); err != nil { + return nil, err + } + // Call the destructor when the object is released. runtime.SetFinalizer(a, finalizer) @@ -185,6 +191,14 @@ func (a *adapter) open(clientOption *options.ClientOptions, databaseName string, a.client = client a.collection = collection + if err = a.prepareIndexes(); err != nil { + return err + } + + return nil +} + +func (a *adapter) prepareIndexes() error { indexes := []string{"ptype", "v0", "v1", "v2", "v3", "v4", "v5"} keysDoc := bson.D{} @@ -195,7 +209,7 @@ func (a *adapter) open(clientOption *options.ClientOptions, databaseName string, keysDoc = append(keysDoc, keyDoc) } - if _, err = collection.Indexes().CreateOne( + if _, err := a.collection.Indexes().CreateOne( context.Background(), mongo.IndexModel{ Keys: keysDoc, diff --git a/go.mod b/go.mod index 39d4e0f..15dbcfc 100644 --- a/go.mod +++ b/go.mod @@ -6,3 +6,17 @@ require ( github.com/casbin/casbin/v2 v2.71.1 go.mongodb.org/mongo-driver v1.12.0 ) + +require ( + github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect + github.com/golang/snappy v0.0.1 // indirect + github.com/klauspost/compress v1.13.6 // indirect + github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect + golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect + golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect + golang.org/x/text v0.7.0 // indirect +)