以下是一个MongoDB连接的代码示例

package database

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func DBSet() *mongo.Client {
	// MongoDBデータベースに接続するクライアントを作成します
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://development:testpassword@localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}

	// タイムアウト用のコンテキストを作成します
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// クライアントがデータベースに接続するようにします
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// データベースへの接続が成功したかを確認します
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Println("MongoDBへの接続に失敗しました")
		return nil
	}

	fmt.Println("MongoDBへの接続に成功しました")
	return client
}

var Client *mongo.Client = DBSet()

func UserData(client *mongo.Client, CollectionName string) *mongo.Collection {
	// 指定されたコレクション名のユーザーデータを操作するためのコレクションを取得します
	var collection *mongo.Collection = client.Database("Ecommerce").Collection(CollectionName)
	return collection
}

func ProductData(client *mongo.Client, CollectionName string) *mongo.Collection {
	// 指定されたコレクション名の製品データを操作するためのコレクションを取得します
	var productcollection *mongo.Collection = client.Database("Ecommerce").Collection(CollectionName)
	return productcollection
}

DBSet()函数用于连接MongoDB数据库并返回连接的客户端。连接使用的是URI,指定的URI是”mongodb://development:testpassword@localhost:27017″。这意味着用户名是”development”,密码是”testpassword”,MongoDB在本地主机的端口27017上运行。

Client变量是一个全局变量,用于保存与数据库的连接。调用DBSet()函数来建立连接,并将该客户端分配给Client变量。

UserData()函数将返回用于操作具有指定集合名称的用户数据的集合。它接受数据库客户端和集合名称作为参数,并获取指定数据库(“Ecommerce”)中指定集合的引用。

ProductData()函数返回一个用于操作具有指定集合名称的产品数据的集合。它接收数据库客户端和集合名称作为参数,并获取指定数据库(“Ecommerce”)中指定集合的引用。

稍后会添加更多详细信息。

bannerAds