英文:
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 &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("PMS").Collection("dataStored")
_, err := collection.InsertOne(ctx, inputData)
return err
}
Also:
- Don't hardcode
context.TODO()
in your production code. Add acontext.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论