2024-03-04 10:03:40 +01:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-03-04 10:19:35 +01:00
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
2024-03-04 10:03:40 +01:00
|
|
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2024-03-04 10:19:35 +01:00
|
|
|
var Client *mongo.Client
|
|
|
|
|
|
|
|
func GetDebtsForPerson(client *mongo.Client, personID string) ([]Debt, error) {
|
|
|
|
var results []Debt
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
// Umwandlung der personID von string in primitive.ObjectID
|
|
|
|
objID, err := primitive.ObjectIDFromHex(personID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Verbindung zur "debts" Sammlung
|
|
|
|
debtsCollection := client.Database("debtlist").Collection("debts")
|
|
|
|
|
|
|
|
// Abfrage erstellen, die alle Schulden findet, deren fk_pid mit der personID übereinstimmt
|
|
|
|
filter := bson.M{"fk_pid": objID}
|
|
|
|
cursor, err := debtsCollection.Find(ctx, filter)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer cursor.Close(ctx)
|
|
|
|
|
|
|
|
// Durchlaufen des Cursors und Hinzufügen der Ergebnisse zur results-Slice
|
|
|
|
for cursor.Next(ctx) {
|
|
|
|
var debt Debt
|
|
|
|
if err := cursor.Decode(&debt); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
results = append(results, debt)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := cursor.Err(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return results, nil
|
|
|
|
}
|
2024-03-04 10:03:40 +01:00
|
|
|
func InsertRandomData(client *mongo.Client) {
|
|
|
|
persons := []string{"Max", "Moritz", "Hans", "Peter", "Paul", "Klaus", "Karl", "Kai", "Kurt", "Karl-Heinz"}
|
|
|
|
debts := []Debt{}
|
|
|
|
for i := 0; i < 10; i++ {
|
|
|
|
person := Person{Name: persons[i]}
|
|
|
|
collection := client.Database("debtlist").Collection("persons")
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
result, err := collection.InsertOne(ctx, person)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
for j := 0; j < 3; j++ {
|
|
|
|
debts = append(debts, Debt{PersonID: result.InsertedID.(primitive.ObjectID), Amount: j * 100, Description: "Test", Datetime: time.Now()})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
collection := client.Database("debtlist").Collection("debts")
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
for _, debt := range debts {
|
|
|
|
_, err := collection.InsertOne(ctx, debt)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|