LoginSignup
0
0

Go mongoDB接続のコード例

Posted at
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を使用しており、"mongodb://development:testpassword@localhost:27017"というURIを指定しています。これは、ユーザー名が"development"、パスワードが"testpassword"で、ローカルホストのポート27017でMongoDBが実行されていることを意味します。

Client変数は、データベースへの接続を保持するためのグローバルな変数です。DBSet()関数を呼び出して接続を確立し、そのクライアントをClient変数に割り当てます。

UserData()関数は、指定されたコレクション名を持つユーザーデータの操作に使用するためのコレクションを返します。引数としてデータベースクライアントとコレクション名を受け取り、指定されたデータベース("Ecommerce")の指定されたコレクションに対する参照を取得します。

ProductData()関数は、指定されたコレクション名を持つ製品データの操作に使用するためのコレクションを返します。引数としてデータベースクライアントとコレクション名を受け取り、指定されたデータベース("Ecommerce")の指定されたコレクションに対する参照を取得します。

//さらなる詳細は後日追記。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0