系列文章目录
第一章 gin初步认识
第二章 设置API
第三章 使用MongoDB数据持久化
目录
注:
- 系列文章是对应上述英文原版书的学习笔记
- 相关自己的练习代码包含注释,放在在本人的gitee,欢迎star
- 所有内容允许转载,如果侵犯书籍的著作权益,请联系删除
- 笔记持续更新中
使用MongoDB数据持久化
前言
本章将会用docker部署MongoDB和Redis,实现CRUD,介绍标准go项目目录结构,优化API响应提高网站性能
go使用mongodb
- 在项目中获取依赖
go get go.mongodb.org/mongo-driver/mongo
这将会下载驱动到系统GOPath,并把其作为依赖写入go.mod文件中
- 连接MongoDB
- docker运行mongodb
docker run -d --name mongodb -e MONGO_INITDB_ROOT_ USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=password -p 27017:27017 mongo:4.4.3
- 使用免费的mongo atlas数据库
- 数据库的连接和测试代码
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"log"
)
var ctx context.Context
var err error
var client *mongo.Client
// 使用环境变量定义的数据库地址
//var uri = os.Getenv("MONGO_URI")
var uri = "***********************************************************"
func init() {
ctx = context.Background()
client, err = mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err = client.Ping(context.TODO(), readpref.Primary()); err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB")
}
func main() {
}
- 使用上一章的数据初始化数据库
func init() {
recipes = make([]model.Recipe, 0)
// 读取文件中的信息
file, _ := ioutil.ReadFile("recipes.json")
// 把信息解析为recipe实体
_ = json.Unmarshal([]byte(file), &recipes)
...
// InsertMany传递的数据参数就是interface
var listOfRecipes []interface{
}
for _, recipe := range recipes {
listOfRecipes = append(listOfRecipes, recipe)
}
collection := client.Database(database_name).Collection(collection_name)
insertManyResult, err := collection.InsertMany(ctx, listOfRecipes)
if err != nil {
log.Fatal(err)
}
log.Println("Inserted recipes: ", len(insertManyResult.InsertedIDs))
}
MongoDB在插入数据的时候,只要没创建,就会默认创建指定数据模型的库(在MongoDB中库叫做collection 集合,插入的记录叫做document 文档)
collection.InsertMany
接收interface{}
切片类型的数据,所以上面把recipes数组的数据循环拷贝到listOfRecipes的interface切片中
recipes.json文件有如下内容