Documentation
¶
Overview ¶
Created by LonelyPale at 2019-12-06
Index ¶
- Constants
- Variables
- func CloseClient(client *Client) error
- func IsErrIndexExists(err error) bool
- func MakeInstance(name string) interface{}
- func RegisterModel(typedNil interface{}, names ...string)
- func TimeoutContext(ts ...time.Duration) (context.Context, context.CancelFunc)
- func Var(field interface{}, name string, mname string, tags ...string) error
- type A
- type AfterDeleter
- type AfterFinder
- type AfterInserter
- type AfterUpdater
- type BeforeDeleter
- type BeforeFinder
- type BeforeInserter
- type BeforeUpdater
- type Client
- func (c *Client) Connect(ctxs ...context.Context) error
- func (c *Client) DB(db ...string) *Database
- func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database
- func (c *Client) Disconnect(ctxs ...context.Context) error
- func (c *Client) GetContext() (context.Context, context.CancelFunc)
- func (c *Client) MongoClient() *mongo.Client
- func (c *Client) StartSession(opts ...*options.SessionOptions) (mongo.Session, error)
- type ClientOptions
- type Collection
- func (coll *Collection) Client() *Client
- func (coll *Collection) Clone(opts ...*CollectionOptions) (*Collection, error)
- func (coll *Collection) Count(ctx context.Context, filter interface{}, opts ...*CountOptions) (int64, error)
- func (coll *Collection) CreateIndex(ctx context.Context, models []mongo.IndexModel, ...) ([]string, error)
- func (coll *Collection) CreateUniqueIndex(keys ...string) ([]string, error)
- func (coll *Collection) Database() *Database
- func (coll *Collection) Delete(ctx context.Context, filter interface{}, opts ...*DeleteOptions) (int64, error)
- func (coll *Collection) DeleteByID(i interface{}) (int64, error)
- func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*DeleteOptions) (int64, error)
- func (coll *Collection) Find(ctx context.Context, result interface{}, filter interface{}, ...) error
- func (coll *Collection) FindByID(result interface{}, i interface{}) error
- func (coll *Collection) FindOne(ctx context.Context, result interface{}, filter interface{}, ...) error
- func (coll *Collection) FindOneAndUpdate(ctx context.Context, result interface{}, filter interface{}, ...) error
- func (coll *Collection) FindOrInsert(ctx context.Context, filter interface{}, document interface{}, ...) (types.ObjectID, error)
- func (coll *Collection) GetContext() (context.Context, context.CancelFunc)
- func (coll *Collection) Insert(ctx context.Context, documents []interface{}, opts ...*InsertManyOptions) ([]types.ObjectID, error)
- func (coll *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*InsertOneOptions) (types.ObjectID, error)
- func (coll *Collection) MongoCollection() *mongo.Collection
- func (coll *Collection) Name() string
- func (coll *Collection) Save(ctx context.Context, document interface{}, opts ...*InsertOneOptions) (types.ObjectID, error)
- func (coll *Collection) Update(ctx context.Context, filter interface{}, updater interface{}, ...) (*mongo.UpdateResult, error)
- func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, updater interface{}, ...) (*mongo.UpdateResult, error)
- type CollectionOptions
- type CountOptions
- type CreateIndexesOptions
- type D
- type Database
- type DeleteOptions
- type E
- type FieldType
- type Filter
- func (f Filter) All(key string, value interface{}) Filter
- func (f Filter) And(values ...interface{}) Filter
- func (f Filter) Delete(key string)
- func (f Filter) Exists(key string, value bool) Filter
- func (f Filter) Get(key string) interface{}
- func (f Filter) Gt(key string, value interface{}) Filter
- func (f Filter) Gte(key string, value interface{}) Filter
- func (f Filter) ID(value interface{}) Filter
- func (f Filter) In(key string, value interface{}) Filter
- func (f Filter) Lt(key string, value interface{}) Filter
- func (f Filter) Lte(key string, value interface{}) Filter
- func (f Filter) Ne(key string, value interface{}) Filter
- func (f Filter) Or(values ...interface{}) Filter
- func (f Filter) Regex(key string, value interface{}) Filter
- func (f Filter) RegexCondition(keys ...string) Filter
- func (f Filter) Set(values ...interface{}) Filter
- func (f Filter) Size(key string, value interface{}) Filter
- func (f Filter) TimeCondition(keys ...string) Filter
- func (f Filter) Type(key string, value interface{}) Filter
- type FindOneAndUpdateOptions
- type FindOneOptions
- type FindOptions
- type IndexModel
- type IndexOptions
- type InsertManyOptions
- type InsertOneOptions
- type M
- type Model
- func (Model) AfterInsert(ctx context.Context, documents []interface{}, opts interface{}, ...) error
- func (Model) BeforeInsert(ctx context.Context, documents []interface{}, opts interface{}) error
- func (Model) BeforeUpdate(ctx context.Context, filter interface{}, updater interface{}, ...) error
- func (m Model) Collection() *Collection
- func (m Model) Create(ctxs ...context.Context) error
- func (m Model) Delete(ctxs ...context.Context) error
- func (m Model) Find(ctxs ...context.Context) error
- func (m Model) FindOrInsert(filter interface{}, ctxs ...context.Context) error
- func (m *Model) Init(doc interface{}, coll *Collection)
- func (m Model) IsInited() bool
- func (m Model) Save(ctxs ...context.Context) error
- func (m Model) Update(ctxs ...context.Context) error
- func (m Model) Validate(tags ...string) error
- type ModelType
- type ModelValidator
- type Paginator
- type Regex
- type Sequence
- type Sort
- type Transaction
- type UpdateOptions
- type Updater
- type ValidateTag
Constants ¶
const ( // go struct field name IDField = "ID" CreateTimeField = "CreateTime" UpdateTimeField = "UpdateTime" // db bson field name IDBson = "_id" // MongoDB ObjectID Field Name CreateTimeBson = "createTime" UpdateTimeBson = "updateTime" // web json field name IDJson = "id" CreateTimeJson = "createTime" UpdateTimeJson = "updateTime" )
Field Constant
const ( ModelValueKey = "ModelValue" InsertOneOptionsKey = "InsertOneOptions" InsertOneResultKey = "InsertOneResult" InsertManyOptionsKey = "InsertManyOptions" InsertManyResultKey = "InsertManyResult" UpdateOptionsKey = "UpdateOptions" UpdateResultKey = "UpdateResult" DeleteOptionsKey = "DeleteOptions" DeleteResultKey = "DeleteResult" FindOneOptionsKey = "FindOneOptions" SingleResultKey = "SingleResult" FindOptionsKey = "FindOptions" ResultKey = "Result" )
const ( OrKey = "$or" AndKey = "$and" InKey = "$in" NinKey = "$nin" AllKey = "$all" NotKey = "$not" NeKey = "$ne" // != GtKey = "$gt" // > GteKey = "$gte" // >= LtKey = "$lt" // < LteKey = "$lte" // <= ModKey = "$mod" // mod 取模运算 ExistsKey = "$exists" TypeKey = "$type" SizeKey = "$size" MatchKey = "$elemMatch" )
Query and Projection Operators
const ( SetKey = "$set" UnsetKey = "$unset" IncKey = "$inc" )
Field Update Operators
const ( CreateTagName = "vCreate" //增 UpdateTagName = "vUpdate" //改 DeleteTagName = "vDelete" //删 FindTagName = "vFind" //查 )
验证tag: 增删查改 CRUD
const DefaultTimeout = 10 * time.Second
Variables ¶
var ErrDocumentExists = errors.New("document already exists")
var ErrDocumentNotExist = errors.New("document does not exist")
var ErrNilCollection = errors.New("collection is nil")
var ErrNilDocument = errors.New("document is nil")
var ErrNilFilter = errors.New("filter cannot be nil")
var ErrNilObjectID = errors.New("ObjectID is nil")
var ErrNilResult = errors.New("the result point cannot be nil")
var ErrNoDocuments = mongo.ErrNoDocuments
var ModelFields = model{
ID: "id",
CreateTime: "createTime",
UpdateTime: "updateTime",
}
Functions ¶
func CloseClient ¶ added in v0.0.6
CloseClient 关闭 MongoDB 客户端
func MakeInstance ¶ added in v0.0.4
func MakeInstance(name string) interface{}
func RegisterModel ¶ added in v0.0.8
func RegisterModel(typedNil interface{}, names ...string)
mongodb.RegisterModel((*User)(nil), UserCollectionName)
func TimeoutContext ¶ added in v0.0.4
Types ¶
type AfterDeleter ¶ added in v0.0.4
type AfterFinder ¶ added in v0.0.4
type AfterInserter ¶ added in v0.0.4
type AfterUpdater ¶ added in v0.0.4
type AfterUpdater interface {
AfterUpdate(ctx context.Context, filter interface{}, updater interface{}, opts []*options.UpdateOptions, result *mongo.UpdateResult) error
}
type BeforeDeleter ¶ added in v0.0.4
type BeforeDeleter interface {
BeforeDelete(ctx context.Context, filter interface{}, opts []*options.DeleteOptions) error
}
type BeforeFinder ¶ added in v0.0.4
type BeforeInserter ¶ added in v0.0.4
type BeforeUpdater ¶ added in v0.0.4
type BeforeUpdater interface {
BeforeUpdate(ctx context.Context, filter interface{}, updater interface{}, opts []*options.UpdateOptions) error
}
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func Connect ¶
func Connect(opts *ClientOptions) (*Client, error)
func GetClient ¶ added in v0.0.6
func GetClient(cfgs ...*config.MongodbConfig) *Client
func (*Client) Database ¶
func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database
func (*Client) GetContext ¶ added in v0.0.4
func (c *Client) GetContext() (context.Context, context.CancelFunc)
func (*Client) MongoClient ¶
func (*Client) StartSession ¶
type ClientOptions ¶
type ClientOptions struct { //custom options URI string //数据库连接字符串 Timeout time.Duration //单位秒 EnableTransaction bool //默认不启用事务,启用事务需要打开副本集 DefaultDBName string //默认的数据库名称 //options.ClientOptions MaxPoolSize uint64 //最大连接池 MinPoolSize uint64 //最小连接池 // contains filtered or unexported fields }
func NewClientOptions ¶
func NewClientOptions(uri string) *ClientOptions
func NewClientOptionsFromConfig ¶
func NewClientOptionsFromConfig(conf *config.MongodbConfig) *ClientOptions
func NewClientOptionsFromFile ¶ added in v0.0.3
func NewClientOptionsFromFile(files ...string) *ClientOptions
func (*ClientOptions) Apply ¶
func (c *ClientOptions) Apply()
type Collection ¶
type Collection struct {
// contains filtered or unexported fields
}
func (*Collection) Client ¶
func (coll *Collection) Client() *Client
func (*Collection) Clone ¶ added in v0.0.4
func (coll *Collection) Clone(opts ...*CollectionOptions) (*Collection, error)
func (*Collection) Count ¶
func (coll *Collection) Count(ctx context.Context, filter interface{}, opts ...*CountOptions) (int64, error)
func (*Collection) CreateIndex ¶ added in v0.0.8
func (coll *Collection) CreateIndex(ctx context.Context, models []mongo.IndexModel, opts ...*options.CreateIndexesOptions) ([]string, error)
创建索引
func (*Collection) CreateUniqueIndex ¶ added in v0.0.8
func (coll *Collection) CreateUniqueIndex(keys ...string) ([]string, error)
创建唯一索引
func (*Collection) Database ¶
func (coll *Collection) Database() *Database
func (*Collection) Delete ¶
func (coll *Collection) Delete(ctx context.Context, filter interface{}, opts ...*DeleteOptions) (int64, error)
func (*Collection) DeleteByID ¶ added in v0.0.8
func (coll *Collection) DeleteByID(i interface{}) (int64, error)
func (*Collection) DeleteOne ¶
func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*DeleteOptions) (int64, error)
func (*Collection) Find ¶
func (coll *Collection) Find(ctx context.Context, result interface{}, filter interface{}, opts ...*FindOptions) error
result 必须是指向切片的指针或指向 Pager 接口的指针
func (*Collection) FindByID ¶ added in v0.0.8
func (coll *Collection) FindByID(result interface{}, i interface{}) error
func (*Collection) FindOne ¶
func (coll *Collection) FindOne(ctx context.Context, result interface{}, filter interface{}, opts ...*FindOneOptions) error
func (*Collection) FindOneAndUpdate ¶ added in v0.0.6
func (coll *Collection) FindOneAndUpdate(ctx context.Context, result interface{}, filter interface{}, update interface{}, opts ...*FindOneAndUpdateOptions) error
func (*Collection) FindOrInsert ¶ added in v0.0.8
func (coll *Collection) FindOrInsert(ctx context.Context, filter interface{}, document interface{}, opts ...*InsertOneOptions) (types.ObjectID, error)
推荐优先使用唯一索引来解决字段的唯一性问题,只有在有性能问题时才使用先查询再插入的方法 查找一条记录,如果不存在,则插入一条记录
func (*Collection) GetContext ¶ added in v0.0.4
func (coll *Collection) GetContext() (context.Context, context.CancelFunc)
func (*Collection) Insert ¶
func (coll *Collection) Insert(ctx context.Context, documents []interface{}, opts ...*InsertManyOptions) ([]types.ObjectID, error)
func (*Collection) InsertOne ¶
func (coll *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*InsertOneOptions) (types.ObjectID, error)
func (*Collection) MongoCollection ¶
func (coll *Collection) MongoCollection() *mongo.Collection
func (*Collection) Name ¶
func (coll *Collection) Name() string
func (*Collection) Save ¶
func (coll *Collection) Save(ctx context.Context, document interface{}, opts ...*InsertOneOptions) (types.ObjectID, error)
todo: 考虑是否用 FindOneAndUpdate 替换,如用 FindOneAndUpdate 替换,则无法调用 Insert、Update callback 创建或更新一条记录
func (*Collection) Update ¶
func (coll *Collection) Update(ctx context.Context, filter interface{}, updater interface{}, opts ...*UpdateOptions) (*mongo.UpdateResult, error)
func (*Collection) UpdateOne ¶
func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, updater interface{}, opts ...*UpdateOptions) (*mongo.UpdateResult, error)
type CollectionOptions ¶ added in v0.0.8
type CollectionOptions = options.CollectionOptions
type CountOptions ¶ added in v0.0.8
type CountOptions = options.CountOptions
type CreateIndexesOptions ¶ added in v0.0.8
type CreateIndexesOptions = options.CreateIndexesOptions
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
func (*Database) Collection ¶
func (db *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection
func (*Database) MongoDatabase ¶
type DeleteOptions ¶ added in v0.0.8
type DeleteOptions = options.DeleteOptions
type Filter ¶ added in v0.0.4
type Filter map[string]interface{}
func NewFilterFromMap ¶ added in v0.0.8
func (Filter) And ¶ added in v0.0.4
{ $and: [ { name: { $ne: "c"} }, { name: { $ne: "go"} } ] } { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
func (Filter) Or ¶ added in v0.0.4
{ $or: [ {name: "c"}, {name: "go"} ] } { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } { $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
func (Filter) RegexCondition ¶ added in v0.0.8
func (Filter) TimeCondition ¶ added in v0.0.8
type FindOneAndUpdateOptions ¶ added in v0.0.8
type FindOneAndUpdateOptions = options.FindOneAndUpdateOptions
type FindOneOptions ¶ added in v0.0.8
type FindOneOptions = options.FindOneOptions
type FindOptions ¶ added in v0.0.8
type FindOptions = options.FindOptions
type IndexModel ¶ added in v0.0.8
type IndexModel = mongo.IndexModel
type IndexOptions ¶ added in v0.0.8
type IndexOptions = options.IndexOptions
type InsertManyOptions ¶ added in v0.0.8
type InsertManyOptions = options.InsertManyOptions
type InsertOneOptions ¶ added in v0.0.8
type InsertOneOptions = options.InsertOneOptions
type Model ¶ added in v0.0.4
type Model struct { ID types.ObjectID `` /* 158-byte string literal not displayed */ CreateTime types.Time `bson:"createTime,omitempty" json:"createTime,omitempty" validate:"omitempty" label:"创建时间"` UpdateTime types.Time `bson:"updateTime,omitempty" json:"updateTime,omitempty" validate:"omitempty" label:"更新时间"` // contains filtered or unexported fields }
type Service interface { Start() (bool, error) OnStart() error Stop() bool OnStop() Reset() (bool, error) OnReset() error IsRunning() bool String() string SetLogger(log.Logger) }
todo: doc可优化为接口类型,如上例
func NewModel ¶ added in v0.0.4
func NewModel(doc interface{}, coll *Collection) Model
func (Model) AfterInsert ¶ added in v0.0.4
func (Model) BeforeInsert ¶ added in v0.0.4
func (Model) BeforeUpdate ¶ added in v0.0.4
func (Model) Collection ¶ added in v0.0.4
func (m Model) Collection() *Collection
func (Model) FindOrInsert ¶ added in v0.0.8
func (*Model) Init ¶ added in v0.0.8
func (m *Model) Init(doc interface{}, coll *Collection)
初始化文档和集合
type ModelType ¶ added in v0.0.8
type ModelType interface { Field(jsonTagName string) FieldType Kind() reflect.Kind Type() reflect.Type }
func GetModelType ¶ added in v0.0.8
type ModelValidator ¶ added in v0.0.8
type Paginator ¶ added in v0.0.6
type Paginator interface { Skip() int64 Limit() int64 Result() interface{} //必须是切片指针 SetTotal(n int64) }
分页器接口 实现接口的方法必须同时是对象 (a A) 或指针 (a *A),否则断言不到此类型的接口。
type Sequence ¶ added in v0.0.6
type Sequence struct { Model `bson:"-" json:"-"` Key string `bson:"key,omitempty" json:"key,omitempty" validate:"omitempty,min=1" vCreate:"required"` Value int64 `bson:"value,omitempty" json:"value,omitempty" validate:"omitempty,gte=1" vCreate:"required"` // contains filtered or unexported fields }
func NewSequence ¶ added in v0.0.6
func NewSequence(coll *Collection) *Sequence
type Transaction ¶
type Transaction struct {
// contains filtered or unexported fields
}
func NewTransaction ¶
func NewTransaction(client *Client) *Transaction
func (*Transaction) Commit ¶
func (t *Transaction) Commit() error
func (*Transaction) Rollback ¶
func (t *Transaction) Rollback() error
func (*Transaction) Run ¶
func (t *Transaction) Run(ctx context.Context, fn func(sctx mongo.SessionContext) error) error
自动执行事务,简化使用过程。
type UpdateOptions ¶ added in v0.0.8
type UpdateOptions = options.UpdateOptions
type Updater ¶ added in v0.0.4
type Updater map[string]interface{}
func NewUpdater ¶ added in v0.0.4
func NewUpdater(values ...interface{}) Updater
func (Updater) Inc ¶ added in v0.0.6
{ $inc: { quantity: -2, "metrics.orders": 1 } } { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
func (Updater) Set ¶ added in v0.0.4
{ $set: { "details.make": "zzz" } } { $set: { "tags.1": "rain gear", "ratings.0.rating": 2 } } { $set: { <field1>: <value1>, ... } }
func (Updater) Unset ¶ added in v0.0.4
{ $unset: { quantity: "", instock: "" } } { $unset: { <field1>: "", ... } }
func (Updater) UpdateTime ¶ added in v0.0.8
Source Files
¶
- alias.go
- callback.go
- client.go
- clientoptions.go
- collection.go
- collection_core.go
- collection_extend.go
- common.go
- constant.go
- context.go
- database.go
- doc.go
- errors.go
- filter.go
- filter_extend.go
- init.go
- model.go
- model_callback.go
- model_field.go
- model_register.go
- mongodb.go
- sequence.go
- sort.go
- transaction.go
- updater.go
- util.go
- validator.go