如何在一个单独的函数中连接到 MongoDB?

huangapple go评论71阅读模式
英文:

How to connect to MongoDB in a separate function?

问题

在这段代码中,我正在使用golang将MongoDB数据库连接起来,并将数据插入其中。我想将Connection()函数与Insertdata()函数(以及其他我创建的函数,如Finddata()Deletedata()等)分开。

但是当我尝试分开它们时,Connection()函数中的client变量会给我一个消息,说它已声明但未使用,而Insertdata()中的client变量会给我一个消息,说它未声明。如何处理这个问题?

func Connection() {
    // 设置客户端选项
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // 连接到MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)
    if err != nil {
        log.Fatal(err)
    }
}

func Insertdata(inputData interface{}) {
    Connection()
    err, collection := client.Database("PMS").Collection("dataStored")
    collection.InsertOne(context.TODO(), inputData)
    if err != nil {
        log.Fatal(err)
    }
}
英文:

In this code, I am connecting the MongoDB database with golang and inserting data in it. I want to separate the Connection() function from Insertdata() function (from other functions also that I made like Finddata(), Deletedata(), etc).

But when I try to separate it, the client variable from Connection() function gives me a message that it is declared but not used and the client variable from Insertdata() gives me a message that it is undeclared. How to handle this?

func Connection() {
	// Set client options
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// Connect to MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
}
func Insertdata(inputData interface{}) {
    Connection()
	err, collection := client.Database("PMS").Collection("dataStored")
	collection.InsertOne(context.TODO(), inputData)
	if err != nil {
		log.Fatal(err)
	}
}

答案1

得分: 1

请注意,你的代码中的Connection()函数没有返回client实例。你需要返回client才能在其他的Insertdata函数中使用它。

此外,我建议你阅读一下mongo-go-driver Github页面上的使用部分。在https://stackoverflow.com/questions/58365838/how-to-reuse-mongodb-connection-in-go中也有一个处理Go中MongoDB连接的很好的示例。

英文:

Please note that the Connection() function in your code does not return the client instance. You would need to return client in order to use it in your other Insertdata function.

Additionally, I suggest to read through the Usage section on the mongo-go-driver Github page. A good example of how to handle MongoDB connections in Go can be also found in https://stackoverflow.com/questions/58365838/how-to-reuse-mongodb-connection-in-go.

答案2

得分: 1

在Go语言中,我们通常将依赖项存储在结构体类型的字段中。定义一个围绕数据库的抽象,该抽象将保存*mongo.Client(或满足该类型的接口):

type DB struct {
  client *mongo.Client
}

DB类型的工厂函数中实例化客户端:

func NewDB(ctx context.Context, uri string) (*DB, error) {
    clientOptions := options.Client().ApplyURI(uri)
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        return nil, err
    }
    db := DB {
        client: client,
    }
    return &db, nil
}

然后将Insertdata声明为*DB的方法(而不是函数)。这样,您将能够通过其接收器在该方法中使用(并重用)客户端。

func (db *DB) Insertdata(ctx context.Context, inputData interface{}) error {
    collection := db.client.Database("PMS").Collection("dataStored")
    _, err := collection.InsertOne(ctx, inputData)
    return err
}

另外:

  • 不要在生产代码中硬编码context.TODO()。添加一个context.Context参数,使相关的函数和方法可以从调用栈的更高层次进行取消。
  • 不要忽略错误。如果无法在函数或方法内处理错误,请将其返回给调用者。
英文:

In Go, we typically store dependencies in struct type fields. Define some abstraction around the database that will hold a *mongo.Client (or an interface satisfied by that type):

<!-- language: go -->

type DB struct {
  client *mongo.Client
}

Instantiate the client once in a factory function for your DB type:

<!-- language: go -->

func NewDB(ctx context.Context, uri string) (*DB, error) {
    clientOptions := options.Client().ApplyURI(uri)
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        return nil, err
    }
    db := DB {
        client: client,
    }
    return &amp;db, nil
}

Then declare Insertdata as a method (not a function) on *DB. That way, you'll be able to use (and re-use) the client within that method through its receiver.

<!-- language: go -->

func (db *DB) Insertdata(ctx context.Context, inputData interface{}) error {
    collection := db.client.Database(&quot;PMS&quot;).Collection(&quot;dataStored&quot;)
    _, err := collection.InsertOne(ctx, inputData)
    return err
}

Also:

  • Don't hardcode context.TODO() in your production code. Add a context.Context parameter to make the relevant functions and methods cancellable from higher up the call stack.
  • Don't ignore errors. If you can't handle them within a function or method, return them to the caller.

huangapple
  • 本文由 发表于 2021年5月24日 14:46:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/67667717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定