package dao import ( "context" "fmt" "time" "github.com/willie68/schematic-service-go/model" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) const dbPort = 32768 const host = "192.168.178.12" const username = "admin" const password = "akteon00" const database = "schematic" const timeout = 1 * time.Minute var client *mongo.Client func init() { uri := fmt.Sprintf("mongodb://%s:%s@%s:%d", username, password, host, dbPort) clientOptions := options.Client() clientOptions.ApplyURI(uri) clientOptions.Auth = &options.Credential{Username: username, Password: password, AuthSource: "admin"} var err error client, err = mongo.NewClient(clientOptions) if err != nil { fmt.Printf("error: %s\n", err.Error()) } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() err = client.Connect(ctx) if err != nil { fmt.Printf("error: %s\n", err.Error()) } } func CreateSchematic(schematic model.Schematic) (string, error) { ctx, _ := context.WithTimeout(context.Background(), timeout) collection := client.Database(database).Collection("schematic") result, err := collection.InsertOne(ctx, schematic) if err != nil { fmt.Printf("error: %s\n", err.Error()) return "", err } filter := bson.M{"_id": result.InsertedID} err = collection.FindOne(ctx, filter).Decode(&schematic) if err != nil { fmt.Printf("error: %s\n", err.Error()) return "", err } return result.InsertedID.(string), nil }