From 688d9797aac27cdef351bd2fc1476b2474d53e13 Mon Sep 17 00:00:00 2001 From: Florian Sylvain Date: Fri, 14 Oct 2022 12:22:36 +0200 Subject: [PATCH] Added getDocuments + refactor --- internal/database.go | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/internal/database.go b/internal/database.go index d8bf30d..82c0976 100644 --- a/internal/database.go +++ b/internal/database.go @@ -2,6 +2,7 @@ package internal import ( "context" + "errors" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" @@ -22,18 +23,31 @@ func getNewClient() *mongo.Client { return client } -func pushDocument(location Location, document interface{}) error { +func getCollection(location Location) *mongo.Collection { client := getNewClient() defer client.Disconnect(context.TODO()) + return client.Database(location.Database).Collection(location.Collection) +} - coll := client.Database(location.Database).Collection(location.Collection) - _, err := coll.InsertOne(context.TODO(), document) +func pushDocument(location Location, document interface{}) error { + collection := getCollection(location) + _, err := collection.InsertOne(context.TODO(), document) if err != nil { return err } - return nil } -// func getDocument(database string, collection string) { -// } +func getDocuments(location Location, filter interface{}) ([][]byte, error) { + collection := getCollection(location) + var results [][]byte + + cursor, err := collection.Find(context.TODO(), filter) + if err != nil { + return results, errors.New("something is wrong with filter to find document") + } + for cursor.TryNext(context.TODO()) { + results = append(results, cursor.Current) + } + return results, nil +}