MongoDB 示例
本项目演示了如何在 Go 应用中使用 Fiber 框架连接到 MongoDB 数据库。
前提条件
确保你已安装以下内容
- Golang
- Fiber 包
- MongoDB
- MongoDB Go 驱动
设置
-
克隆仓库
git clone https://github.com/gofiber/recipes.git
cd recipes/mongodb -
安装依赖
go get
-
设置你的 MongoDB 数据库并更新代码中的连接字符串。
运行应用
- 启动应用
go run main.go
示例
这里是在 Fiber 应用中连接 MongoDB 数据库的示例
package main
import (
"context"
"log"
"time"
"github.com/gofiber/fiber/v2"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// MongoDB connection
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://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)
}
defer client.Disconnect(ctx)
// Fiber instance
app := fiber.New()
// Routes
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, MongoDB!")
})
// Start server
log.Fatal(app.Listen(":3000"))
}