Documentation
¶
Overview ¶
Package db 提供 MongoDB 连接的 wire provider(公共基础设施)。 各服务在 wire 装配时直接复用 MongoSet,无需重复实现连接逻辑。
Index ¶
- Variables
- func EnsureIndexesFromFile(db *mongo.Database, filePath string) error
- func NewClient() (*mongo.Client, error)
- func NewDatabase(client *mongo.Client) (*mongo.Database, error)
- func WithTransaction(client *mongo.Client, ctx context.Context, fn func(ctx context.Context) error) error
- type CollectionIndexes
- type IndexSpec
- type KeyVal
Constants ¶
This section is empty.
Variables ¶
View Source
var MongoSet = wire.NewSet(NewClient, NewDatabase)
MongoSet 公共 provider 集合,各服务 wire 装配时引入。
Functions ¶
func EnsureIndexesFromFile ¶
EnsureIndexesFromFile 按 JSON 索引清单同步集合索引:
- 创建清单中缺失的索引;
- 删除集合中不在清单里的索引(清单是唯一事实来源),但保留系统索引 _id_。
清单格式(数组):
[
{ "collection": "Directory", "indexes": [
{ "name": "idx_x", "keys": [{"f":"tenant_id","v":1}, {"f":"domain","v":1}], "unique": true }
]}
]
func NewDatabase ¶
NewDatabase wire provider:根据 client 返回库实例。
func WithTransaction ¶
func WithTransaction(client *mongo.Client, ctx context.Context, fn func(ctx context.Context) error) error
WithTransaction 在 MongoDB 事务中执行 fn。
用法:跨多个集合/仓储的批量写(如"删除目录域连带删用户/组织")需要 要么全成功要么全回滚时,用此函数包裹;fn 收到的 ctx 为事务会话上下文, 各仓储方法传入它即可自动进入同一事务(前提是各仓储复用同一个 client)。
注意:多文档事务要求 MongoDB 副本集(replica set),standalone 会报错。
Types ¶
type CollectionIndexes ¶
type CollectionIndexes struct {
Collection string `json:"collection"`
Indexes []IndexSpec `json:"indexes"`
}
CollectionIndexes 一个集合的索引清单
type IndexSpec ¶
type IndexSpec struct {
Keys []KeyVal `json:"keys"` // [{"f":"tenant_id","v":1}, {"f":"domain","v":1}](有序)
Unique bool `json:"unique,omitempty"` // 是否唯一索引
Name string `json:"name,omitempty"` // 索引名,缺省由 mongo 自动命名
PartialFilterExpression bson.M `json:"partialFilterExpression,omitempty"` // 部分索引过滤条件(如 {"is_deleted": false},配合假删除)
}
IndexSpec 单个索引定义(对应 JSON 中一个索引)
Click to show internal directories.
Click to hide internal directories.