How to use GetMongoDataBase method of storage Package

Best Testkube code snippet using storage.GetMongoDataBase

repository.go

Source:repository.go Github

copy

Full Screen

1package repository2import (3 "context"4 "errors"5 "github.com/nkonev/blog-storage/logger"6 . "github.com/nkonev/blog-storage/logger"7 "github.com/nkonev/blog-storage/utils"8 "go.mongodb.org/mongo-driver/bson"9 "go.mongodb.org/mongo-driver/bson/primitive"10 "go.mongodb.org/mongo-driver/mongo"11 "go.mongodb.org/mongo-driver/mongo/options"12)13const Id = "_id"14const filename = "filename"15const published = "published"16const userId = "userid"17const collectionLimits = "limits"18const CollectionUserFiles = "userFiles"19// https://vkt.sh/go-mongodb-driver-cookbook/20type UserFileDto struct {21 Id primitive.ObjectID `bson:"_id,omitempty"` // mongo document id equal to minio object jd22 Filename string23 Published bool24 UserId int6425}26type UserFileRepository struct {27 mongo *mongo.Client28}29func NewUserFileRepository(mongo *mongo.Client) *UserFileRepository {30 return &UserFileRepository{mongo: mongo}31}32type LimitsRepository struct {33 mongo *mongo.Client34}35func NewLimitsRepository(mongo *mongo.Client) *LimitsRepository {36 return &LimitsRepository{mongo: mongo}37}38func ToFileMongoDto(c *mongo.Cursor) (*UserFileDto, error) {39 var elem UserFileDto40 err := c.Decode(&elem)41 if err != nil {42 return nil, err43 }44 return &elem, nil45}46func GetIdDoc(objectId string) (*bson.D, error) {47 ids, e := primitive.ObjectIDFromHex(objectId)48 if e != nil {49 return nil, e50 }51 ds := bson.D{{Id, ids}}52 return &ds, nil53}54func GetUpdateDoc(p bson.M) bson.M {55 update := bson.M{"$set": p}56 return update57}58func (r *UserFileRepository) GetUserIdByGlobalId(objectId string) (int, error) {59 ids, e := primitive.ObjectIDFromHex(objectId)60 if e != nil {61 return 0, e62 }63 database := utils.GetMongoDatabase(r.mongo)64 ms := bson.M{Id: ids}65 one := database.Collection(CollectionUserFiles).FindOne(context.TODO(), ms)66 if one.Err() != nil {67 if one.Err() != mongo.ErrNoDocuments {68 logger.Logger.Errorf("Error during get user id by global id %v", objectId)69 } else {70 logger.Logger.Infof("No documents found by global id %v", objectId)71 }72 return 0, one.Err()73 }74 var elem UserFileDto75 if err := one.Decode(&elem); err != nil {76 return 0, err77 }78 return int(elem.UserId), nil79}80func (r *UserFileRepository) InsertMetaInfoToMongo(filename string, userId int) (*string, error) {81 database := utils.GetMongoDatabase(r.mongo)82 inserted, err := database.Collection(CollectionUserFiles).InsertOne(context.TODO(), UserFileDto{Filename: filename, Published: false, UserId: int64(userId)})83 if err != nil {84 Logger.Errorf("Error during create mongo metadata document: %v", err)85 return nil, err86 }87 idMongo := inserted.InsertedID.(primitive.ObjectID).Hex()88 return &idMongo, nil89}90func (r *UserFileRepository) GetMetainfoFromMongo(objectId string) (*UserFileDto, error) {91 database := utils.GetMongoDatabase(r.mongo)92 var userFilesCollection *mongo.Collection = database.Collection(CollectionUserFiles)93 ds, err := GetIdDoc(objectId)94 if err != nil {95 logger.Logger.Errorf("Error during creating id document %v", objectId)96 return nil, err97 }98 one := userFilesCollection.FindOne(context.TODO(), ds)99 if one == nil {100 return nil, errors.New("Unexpected nil by id " + objectId)101 }102 if one.Err() != nil {103 logger.Logger.Errorf("Error during querying record from mongo by key %v", objectId)104 return nil, one.Err()105 }106 var elem UserFileDto107 if err := one.Decode(&elem); err != nil {108 if err == mongo.ErrNoDocuments {109 logger.Logger.Errorf("No documents found by key %v", objectId)110 }111 return nil, err112 }113 return &elem, nil114}115func (r *UserFileRepository) RenameUserFile(objId string, newname string) error {116 database := utils.GetMongoDatabase(r.mongo)117 var userFilesCollection *mongo.Collection = database.Collection(CollectionUserFiles)118 findDocument, err := GetIdDoc(objId)119 if err != nil {120 return err121 }122 updateDocument := GetUpdateDoc(primitive.M{filename: newname})123 one := userFilesCollection.FindOneAndUpdate(context.TODO(), findDocument, updateDocument)124 if one == nil {125 return errors.New("Unexpected nil result during update")126 }127 if one.Err() != nil {128 return one.Err()129 }130 return nil131}132func (r *UserFileRepository) UpdatePublished(objId string, setValPublished bool) (*UserFileDto, error) {133 database := utils.GetMongoDatabase(r.mongo)134 var collection *mongo.Collection = database.Collection(CollectionUserFiles)135 findDocument, err := GetIdDoc(objId)136 if err != nil {137 return nil, err138 }139 updateDocument := GetUpdateDoc(primitive.M{published: setValPublished})140 one := collection.FindOneAndUpdate(context.TODO(), findDocument, updateDocument)141 if one == nil {142 return nil, errors.New("Unexpected nil result during update")143 }144 if one.Err() != nil {145 return nil, one.Err()146 }147 var elem UserFileDto148 if err := one.Decode(&elem); err != nil {149 return nil, err150 }151 return &elem, nil152}153func (r *UserFileRepository) FindUserFiles(userIdInt int) (*mongo.Cursor, error) {154 database := utils.GetMongoDatabase(r.mongo)155 var collection *mongo.Collection = database.Collection(CollectionUserFiles)156 return collection.Find(context.TODO(), bson.D{{userId, userIdInt}})157}158func (r *UserFileRepository) Delete(objId string) error {159 database := utils.GetMongoDatabase(r.mongo)160 var collection *mongo.Collection = database.Collection(CollectionUserFiles)161 d, e := GetIdDoc(objId)162 if e != nil {163 return e164 }165 _, e = collection.DeleteOne(context.TODO(), d)166 return e167}168func IsDocumentExists(mongoC *mongo.Client, collection string, request interface{}, opts ...*options.FindOneOptions) (bool, error) {169 database := utils.GetMongoDatabase(mongoC)170 // https://siongui.github.io/2017/03/13/go-pass-slice-or-array-as-variadic-parameter/#id12171 res := database.Collection(collection).FindOne(context.TODO(), request, opts[:]...)172 if res.Err() != nil {173 if res.Err() == mongo.ErrNoDocuments {174 return false, nil175 }176 Logger.Errorf("Error during find '%v' : %v", request, res.Err())177 return false, res.Err()178 }179 _, e := res.DecodeBytes()180 if e != nil {181 Logger.Errorf("Error during DecodeBytes '%v' : %v", request, res.Err())182 return false, e183 } else {184 return true, nil185 }186}187func (r *LimitsRepository) IsStorageUnlimitedForUser(userId int) (bool, error) {188 return IsDocumentExists(r.mongo, collectionLimits, bson.D{{Id, userId}})189}190func (r *LimitsRepository) Patch(userId int, limited bool) error {191 database := utils.GetMongoDatabase(r.mongo)192 if limited {193 _, e := database.Collection(collectionLimits).DeleteOne(context.TODO(), bson.D{{Id, userId}})194 if e != nil {195 return e196 }197 } else {198 // unlimited199 _, e := database.Collection(collectionLimits).InsertOne(context.TODO(), bson.D{{Id, userId}})200 if e != nil {201 return e202 }203 }204 return nil205}...

Full Screen

Full Screen

mongo_lock.go

Source:mongo_lock.go Github

copy

Full Screen

1package mongo_lock2import (3 "context"4 . "github.com/nkonev/blog-storage/logger"5 "github.com/nkonev/blog-storage/utils"6 "go.mongodb.org/mongo-driver/bson"7 "go.mongodb.org/mongo-driver/mongo"8 "go.mongodb.org/mongo-driver/mongo/options"9 "time"10)11type mongoLock struct {12 mongoClient *mongo.Client13 lockCollection string14 idDoc bson.D15}16func GetIdDoc() bson.D {17 return bson.D{{"_id", 42}}18}19func NewMongoLock(mongoClient *mongo.Client, lockCollection string) *mongoLock {20 return &mongoLock{mongoClient: mongoClient, lockCollection: lockCollection, idDoc: GetIdDoc()}21}22func createBson(data string) bson.D {23 bdoc := bson.D{}24 err := bson.UnmarshalExtJSON([]byte(data), true, &bdoc)25 if err != nil {26 Logger.Panicf("Error during creating bson from \"%v\": %v", data, err)27 }28 return bdoc29}30func ensureIndex(client *mongo.Client, lockCollection string) {31 database := utils.GetMongoDatabase(client)32 commandResult := database.RunCommand(context.TODO(), createBson(`{33 "createIndexes": "`+lockCollection+`",34 "indexes": [35 {36 "key": {37 "id": 138 },39 "name": "unique_id",40 "unique": true41 }42 ]43}`))44 if commandResult.Err() != nil {45 Logger.Panicf("Error during creating unique index: %v", commandResult.Err())46 }47}48func getUpdateDoc(p bson.M) bson.M {49 update := bson.M{"$set": p}50 return update51}52func (ml *mongoLock) AcquireLock() {53 ensureIndex(ml.mongoClient, ml.lockCollection)54 database := utils.GetMongoDatabase(ml.mongoClient)55 var upsert = true56 duration, _ := time.ParseDuration("1s")57 for {58 result, err := database.Collection(ml.lockCollection).UpdateOne(context.TODO(), ml.idDoc, getUpdateDoc(bson.M{"lastAcquired": time.Now()}), &options.UpdateOptions{Upsert: &upsert})59 if err != nil {60 Logger.Panicf("Error during acquiring lock: %v", err)61 } else {62 if result.UpsertedID != nil {63 Logger.Infof("Lock has been acquired")64 break65 } else {66 Logger.Infof("Lock has n' t been acquired - waiting %v", duration)67 time.Sleep(duration)68 continue69 }70 }71 }72}73func (ml *mongoLock) ReleaseLock() {74 database := utils.GetMongoDatabase(ml.mongoClient)75 _, err := database.Collection(ml.lockCollection).DeleteOne(context.TODO(), ml.idDoc)76 if err != nil {77 Logger.Panicf("Error during releasing lock: %v", err)78 }79 Logger.Infof("Lock successfully released")80}...

Full Screen

Full Screen

db.go

Source:db.go Github

copy

Full Screen

1package db2import (3 "github.com/flavioribeiro/gonfig"4 "github.com/snickers/snickers/types"5)6//go:generate counterfeiter . Storage7// Storage defines functions for accessing data8type Storage interface {9 // Preset methods10 StorePreset(types.Preset) (types.Preset, error)11 RetrievePreset(string) (types.Preset, error)12 UpdatePreset(string, types.Preset) (types.Preset, error)13 GetPresets() ([]types.Preset, error)14 DeletePreset(string) (types.Preset, error)15 // Job methods16 DeleteJob(string) (types.Job, error)17 StoreJob(types.Job) (types.Job, error)18 RetrieveJob(string) (types.Job, error)19 UpdateJob(string, types.Job) (types.Job, error)20 GetJobs() ([]types.Job, error)21 ClearDatabase() error22}23// GetDatabase selects the right driver based on config24func GetDatabase(config gonfig.Gonfig) (Storage, error) {25 driver, err := config.GetString("DATABASE_DRIVER", "memory")26 if err != nil {27 return nil, err28 }29 if driver == "mongo" || driver == "mongodb" {30 return getMongoDatabase(config)31 }32 return getMemoryDatabase()33}...

Full Screen

Full Screen

GetMongoDataBase

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 s := storage.Storage{}4 db := s.GetMongoDataBase()5 fmt.Println("db: ", db)6}7db: &{0xc0000a61e0 0xc0000a61e0 0xc0000a61e0 0xc0000a61e0}8How to use import in Go9How to use import in Go

Full Screen

Full Screen

GetMongoDataBase

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 storageObject := storage.Storage{}4 mongoDataBase := storageObject.GetMongoDataBase()5 fmt.Println("mongoDataBase: ", mongoDataBase)6}7Go: How to import packages in Go - September 3, 2020

Full Screen

Full Screen

GetMongoDataBase

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 storage := storage.NewStorage()4 db := storage.GetMongoDataBase()5 fmt.Println(db)6}7import (8func main() {9 storage := storage.NewStorage()10 db := storage.GetMongoDataBase()11 fmt.Println(db)12}13import (14func main() {15 storage := storage.NewStorage()16 db := storage.GetMongoDataBase()17 fmt.Println(db)18}19import (20func main() {21 storage := storage.NewStorage()22 db := storage.GetMongoDataBase()23 fmt.Println(db)24}25import (26func main() {27 storage := storage.NewStorage()28 db := storage.GetMongoDataBase()29 fmt.Println(db)30}31import (32func main() {33 storage := storage.NewStorage()34 db := storage.GetMongoDataBase()35 fmt.Println(db)36}37import (38func main() {39 storage := storage.NewStorage()40 db := storage.GetMongoDataBase()41 fmt.Println(db)42}

Full Screen

Full Screen

GetMongoDataBase

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 db := storage.GetMongoDataBase()4 fmt.Println(db)5}6import (7func GetMongoDataBase() *mgo.Database {8 session, err := mgo.Dial("localhost")9 if err != nil {10 panic(err)11 }12 defer session.Close()13 session.SetSafe(&mgo.Safe{})14 c := session.DB("test").C("people")15 err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},16 &Person{"Cla", "+55 53 8402 8510"})17 if err != nil {18 panic(err)19 }20 result := Person{}21 err = c.Find(bson.M{"name": "Ale"}).One(&result)22 if err != nil {23 panic(err)24 }25 fmt.Println("Phone:", result.Phone)26 return session.DB("test")27}28import "gopkg.in/mgo.v2/bson"29type Person struct {30}31func GetPerson() Person {32 return Person{"Ale", "+55 53 8116 9639"}33}34import (35func main() {

Full Screen

Full Screen

GetMongoDataBase

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 db := storage.GetMongoDataBase()4 collection := db.C("users")5 fmt.Println("Collection name:", collection.Name)6}7import (8func main() {9 db := storage.GetMongoDataBase()10 collection := db.C("users")11 fmt.Println("Collection name:", collection.Name)12}13import (14func main() {15 db := storage.GetMongoDataBase()16 collection := db.C("users")17 fmt.Println("Collection name:", collection.Name)18}19import (20func main() {21 db := storage.GetMongoDataBase()22 collection := db.C("users")23 fmt.Println("Collection name:", collection.Name)24}25import (26func main() {27 db := storage.GetMongoDataBase()28 collection := db.C("users")29 fmt.Println("Collection name:", collection.Name)30}31import (32func main() {

Full Screen

Full Screen

GetMongoDataBase

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 db := mongo.GetMongoDataBase()4 collection := db.C("users")5 cursor := collection.Find(nil)6 err := cursor.All(&result)7 if err != nil {8 log.Fatal(err)9 }10 cursor.Close()11 fmt.Println(result)12}13import (14func main() {15 db := mongo.GetMongoDataBase()16 collection := db.C("users")17 cursor := collection.Find(nil)18 err := cursor.All(&result)19 if err != nil {20 log.Fatal(err)21 }22 cursor.Close()23 fmt.Println(result)24}25import (26func main() {

Full Screen

Full Screen

GetMongoDataBase

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func main() {5 mongoDataBase := storage.GetMongoDataBase()6 collection := mongoDataBase.GetCollection("person")7 result := collection.Find(bson.M{})8 var documents []interface{}9 err := result.All(&documents)10 if err != nil {11 panic(err)12 }13 for _, document := range documents {14 person := document.(Person)15 fmt.Println(person.Name, person.Age)16 }17}18import (19type Person struct {20}21func main() {22 mongoDataBase := storage.GetMongoDataBase()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful