mongol

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 26, 2022 License: MIT Imports: 9 Imported by: 0

README

Mongol

Go Reference codecov Go workflow Go Report Card

Model Example

type ExampleModel struct {
	mongol.BaseDocument `bson:",inline"`
	// Default fields from BaseDocument
	//
	// ID        primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
	// CreatedAt time.Time          `json:"created_at" bson:"created_at"`
	// UpdatedAt time.Time          `json:"updated_at" bson:"updated_at"`

	Title string `json:"title,omitempty" bson:"title,omitempty"`
}

Storage usage example

storage, connErr = NewBaseCollection(context.TODO(), mongoURI, mongoDBName, mongoCollectionName)

m := &ExampleModel{}

id, saveErr := storage.InsertOne(context.TODO(), m)

Fiilter example


newM := &ExampleModel{}

err := storage.GetOneByFilter(
	context.TODO(),
	NewFilterBuilder().EqualTo("_id", m.ID).GetQuery(),
	newM,
)

if err != nil {
	fmt.Printf("%#v", newM)
}

Run tests

make test-all
MONGODB_URI=mongodb://localhost:27017 go test -a -v ./...

Documentation

Index

Constants

View Source
const (
	CollectionIDKey          = "_id"
	CreateIndexMethod        = "CreateIndex"
	InsertOneMethod          = "InsertOne"
	InsertManyMethod         = "InsertMany"
	UpdateOneMethod          = "UpdateOne"
	UpdateManyMethod         = "UpdateMany"
	UpdateManyByFilterMethod = "UpdateManyByFilter"
	ReplaceOneMethod         = "ReplaceOne"
	ReplaceOneByIDMethod     = "ReplaceOneByID"
	GetOneByIDMethod         = "GetOneByID"
	GetOneByFilterMethod     = "GetOneByFilter"
	GetManyByFilterMethod    = "GetManyByFilter"
	FindAllByFilterMethod    = "FindAllByFilter"
	FindManyByFilterMethod   = "FindManyByFilter"
	UpsertOneMethod          = "UpsertOne"
	FindAndUpdateOneMethod   = "FindAndUpdateOne"
	DeleteManyMethod         = "DeleteMany"
	DeleteManyByFilterMethod = "DeleteManyByFilter"
	DeleteOneByIDMethod      = "DeleteOneByID"
	DeleteAllMethod          = "DeleteAll"
	CloseCursorTimeout       = time.Second * 1
	FetchTimeout             = time.Second * 1
	QueryTimeout             = time.Second * 1
	FilterTimeout            = time.Second * 1
)
View Source
const (
	// numeric code for MongoDB duplication error
	DuplicationErrorCode = 11000
)

Variables

View Source
var (
	// ErrDocumentNotFound appears then the document was not found in the collection
	ErrDocumentNotFound = errors.New("can not find document")
	// ErrDocumentDuplication appears then the document has fields that already exists in another document
	ErrDocumentDuplication = errors.New("documents duplication was detected")
	// ErrDocumentNotModified appears then the document was not modified after your request
	ErrDocumentNotModified = errors.New("document wasn't modified")
	// ErrInvalidObjectID appears then the ID has invalid format
	ErrInvalidObjectID = errors.New("invalid objectID")
)

Functions

func HandleDuplicationErr

func HandleDuplicationErr(err error) error

HandleDuplicationErr() checks exception type if the error has occurred due to duplication problem then the method returns ErrDocumentDuplication

func IsValidMongoID

func IsValidMongoID(id string) bool

IsValidMongoID() validates provided mongoid string

func ObjectIDsFromStrArr

func ObjectIDsFromStrArr(idsRaw []string) ([]*primitive.ObjectID, error)

ObjectIDsFromStrArr() converts provided array of mongoid strings to ObjectID

func StringToObjectID

func StringToObjectID(hexID string) (primitive.ObjectID, error)

StringToObjectID() converts the string to Mongo ObjectID

Types

type BaseCollection

type BaseCollection struct {
	Client         *Client
	DBName         string
	CollectionName string
	BeforeHooks    map[string][]Hook
	AfterHooks     map[string][]Hook
}

BaseCollection

func NewBaseCollection

func NewBaseCollection(ctx context.Context, mongoURI, dbName, collectionName string) (*BaseCollection, error)

NewBaseCollection() is a constructor for BaseCollection struct

func NewBaseCollectionWithClient

func NewBaseCollectionWithClient(client *Client, dbName, collectionName string) *BaseCollection

NewBaseCollectionWithClient() is a constructor for BaseCollection struct

func (*BaseCollection) AddAfterHook

func (s *BaseCollection) AddAfterHook(methodName string, h Hook)

func (*BaseCollection) AddBeforeHook

func (s *BaseCollection) AddBeforeHook(methodName string, h Hook)

func (*BaseCollection) Collection added in v0.2.0

func (s *BaseCollection) Collection() *mongo.Collection

Collection() returns *mongo.Collection

func (*BaseCollection) CountByFilter

func (s *BaseCollection) CountByFilter(
	ctx context.Context,
	filter interface{},
) (int64, error)

CountByFilter

func (*BaseCollection) CreateIndex

func (s *BaseCollection) CreateIndex(ctx context.Context, k interface{}, o *options.IndexOptions) (string, error)

CreateIndex creates new index

func (*BaseCollection) Database added in v0.2.0

func (s *BaseCollection) Database() *mongo.Database

Database() returns *mongo.Database

func (*BaseCollection) DeleteAll

func (s *BaseCollection) DeleteAll(ctx context.Context) error

DropAll() deletes collection from database

func (*BaseCollection) DeleteManyByFilter

func (s *BaseCollection) DeleteManyByFilter(
	ctx context.Context,
	filter interface{},
	opts ...*options.DeleteOptions,
) (*mongo.DeleteResult, error)

DeleteManyByFilter() documents by given filters

func (*BaseCollection) DeleteOneByID

func (s *BaseCollection) DeleteOneByID(ctx context.Context, docID string) error

DeleteOneByID() deletes document by given ID

func (*BaseCollection) FindAllByFilter

func (s *BaseCollection) FindAllByFilter(
	ctx context.Context,
	filter interface{},
	docs interface{},
	opts ...*options.FindOptions,
) error

FindAllByFilter()

func (*BaseCollection) FindAndUpdateOne added in v0.1.3

func (s *BaseCollection) FindAndUpdateOne(
	ctx context.Context,
	filter interface{},
	update bson.M,
	m Document,
) (Document, error)

FindAndUpdate - find and update existing record. Returns updated model.

func (*BaseCollection) FindManyByFilter

func (s *BaseCollection) FindManyByFilter(
	ctx context.Context,
	filter interface{},
	opts ...*options.FindOptions,
) (*mongo.Cursor, error)

FindManyByFilter()

func (*BaseCollection) GetManyByFilter

func (s *BaseCollection) GetManyByFilter(
	ctx context.Context,
	filter interface{},
	modelBuilder func() Document,
	opts ...*options.FindOptions,
) ([]Document, error)

GetManyByFilter()

func (*BaseCollection) GetOneByFilter

func (s *BaseCollection) GetOneByFilter(
	ctx context.Context,
	filter interface{},
	m Document,
	opts ...*options.FindOneOptions,
) error

GetOneByFilter() is trying to find Document by provided filter

func (*BaseCollection) GetOneByID

func (s *BaseCollection) GetOneByID(
	ctx context.Context,
	recordID string,
	m Document,
	opts ...*options.FindOneOptions,
) error

GetOneByID() is trying to find Document by given recordID

func (*BaseCollection) InsertMany

func (s *BaseCollection) InsertMany(ctx context.Context, docs []interface{}, opts ...*options.InsertManyOptions) ([]string, error)

InsertMany()

func (*BaseCollection) InsertOne

func (s *BaseCollection) InsertOne(ctx context.Context, m Document, opts ...*options.InsertOneOptions) (string, error)

InsertOne() inserts given Document and returns an ID of inserted document

func (*BaseCollection) MongoClient added in v0.2.0

func (s *BaseCollection) MongoClient() *mongo.Client

MongoClient() returns *mongo.Client

func (*BaseCollection) Ping

func (s *BaseCollection) Ping(ctx context.Context) error

Ping() the mongo server

func (*BaseCollection) ReplaceOne

func (s *BaseCollection) ReplaceOne(
	ctx context.Context,
	filter interface{},
	m Document,
	opts ...*options.ReplaceOptions,
) (*mongo.UpdateResult, error)

ReplaceOne

func (*BaseCollection) ReplaceOneByID

func (s *BaseCollection) ReplaceOneByID(
	ctx context.Context,
	recordID string,
	m Document,
	opts ...*options.ReplaceOptions,
) (*mongo.UpdateResult, error)

ReplaceOneByID()

func (*BaseCollection) UpdateMany

func (s *BaseCollection) UpdateMany(
	ctx context.Context,
	filter, update interface{},
	opts ...*options.UpdateOptions,
) (*mongo.UpdateResult, error)

UpdateMany()

func (*BaseCollection) UpdateManyByFilter

func (s *BaseCollection) UpdateManyByFilter(ctx context.Context, filter interface{}, m Document, opts ...*options.UpdateOptions) error

UpdateByFilter() updates given Document according to provided filter

func (*BaseCollection) UpdateOne

func (s *BaseCollection) UpdateOne(ctx context.Context, m Document, opts ...*options.UpdateOptions) error

UpdateOne() updates given Document

func (*BaseCollection) UpsertOne

func (s *BaseCollection) UpsertOne(
	ctx context.Context,
	filter interface{},
	update bson.M,
	m Document,
) (Document, error)

UpsertOne - insert or update existing record. Returns updated model.

type BaseDocument

type BaseDocument struct {
	ID        primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
	CreatedAt time.Time          `json:"created_at" bson:"created_at,omitempty"`
	UpdatedAt time.Time          `json:"updated_at" bson:"updated_at,omitempty"`
}

BaseDocument

func (*BaseDocument) GetHexID

func (m *BaseDocument) GetHexID() string

GetHexID() returns ID of the document as a hex-string

func (*BaseDocument) GetID

func (m *BaseDocument) GetID() primitive.ObjectID

GetID() returns ID of the document

func (*BaseDocument) SetHexID

func (m *BaseDocument) SetHexID(hexID string) error

SetHexID() sets ID of the document from the hex-string

func (*BaseDocument) SetJSONID

func (m *BaseDocument) SetJSONID(jsonB []byte) error

SetJSONID() sets the model ID from given JSON

func (*BaseDocument) SetupCreatedAt added in v0.1.1

func (m *BaseDocument) SetupCreatedAt()

SetupCreatedAt() sets CreatedAt field for the model The method does not store any data to database you should use the method before InsertMany(), UpdateMany() requests from you storage

func (*BaseDocument) SetupUpdatedAt added in v0.1.1

func (m *BaseDocument) SetupUpdatedAt()

SetupUpdatedAt() sets UpdatedAt field for the model The method does not store any data to database you should use the method before InsertMany(), UpdateMany() requests from you storage

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client

func NewClient

func NewClient(ctx context.Context, mongoURI string) (*Client, error)

func (*Client) MongoClient added in v0.2.0

func (c *Client) MongoClient() *mongo.Client

GetMongoClient

type Document

type Document interface {
	GetID() primitive.ObjectID
	GetHexID() string
	SetHexID(hexID string) error
	SetJSONID(jsonB []byte) error
	SetupCreatedAt()
	SetupUpdatedAt()
}

Document

type FilterBuilder added in v1.0.1

type FilterBuilder struct {
	// contains filtered or unexported fields
}

FilterBuilder

func NewFilterBuilder added in v1.0.1

func NewFilterBuilder() *FilterBuilder

NewFilterBuilder() initializes a new FilterBuilder

func (*FilterBuilder) And added in v1.0.1

func (fb *FilterBuilder) And(query ...interface{}) *FilterBuilder

And() allows to combine few queries with $and

func (*FilterBuilder) EqualTo added in v1.0.1

func (fb *FilterBuilder) EqualTo(key string, value interface{}) *FilterBuilder

EqualTo() implements $eq condition for the query

func (*FilterBuilder) GetQuery added in v1.0.1

func (fb *FilterBuilder) GetQuery() bson.M

GetQuery() returns compiled query for *FilterBuilder

func (*FilterBuilder) Gt added in v1.0.1

func (fb *FilterBuilder) Gt(key string, value interface{}) *FilterBuilder

Gt() implements $gt condition for the query

func (*FilterBuilder) Gte added in v1.0.1

func (fb *FilterBuilder) Gte(key string, value interface{}) *FilterBuilder

Gte() implements $gte condition for the query

func (*FilterBuilder) HasField added in v1.0.1

func (fb *FilterBuilder) HasField(key string) *FilterBuilder

HasField() implements $exists:true condition for the query

func (*FilterBuilder) HasNotField added in v1.0.1

func (fb *FilterBuilder) HasNotField(key string) *FilterBuilder

HasNotField() implements $exists:false condition for the query

func (*FilterBuilder) In added in v1.0.1

func (fb *FilterBuilder) In(key string, values bson.A) *FilterBuilder

In() implements $in condition for the query

func (*FilterBuilder) Lt added in v1.0.1

func (fb *FilterBuilder) Lt(key string, value interface{}) *FilterBuilder

Lt() implements $lt condition for the query

func (*FilterBuilder) Lte added in v1.0.1

func (fb *FilterBuilder) Lte(key string, value interface{}) *FilterBuilder

Lte() implements $lte condition for the query

func (*FilterBuilder) NotEqualTo added in v1.0.1

func (fb *FilterBuilder) NotEqualTo(key string, value interface{}) *FilterBuilder

NotEqualTo() implements $ne condition for the query

func (*FilterBuilder) NotIn added in v1.0.1

func (fb *FilterBuilder) NotIn(key string, values bson.A) *FilterBuilder

NotIn() implements $nin condition for the query

func (*FilterBuilder) Or added in v1.0.1

func (fb *FilterBuilder) Or(query ...interface{}) *FilterBuilder

Or() allows to combine few queries with $or

func (*FilterBuilder) Where added in v1.0.1

func (fb *FilterBuilder) Where(key string, query bson.M) *FilterBuilder

Where() allows to set custom conditions for the query

type Hook

type Hook func(ctx context.Context) error

Hook

type Storage

type Storage interface {
	AddBeforeHook(methodName string, h Hook)
	AddAfterHook(methodName string, h Hook)
	Ping(ctx context.Context) error
	Collection() *mongo.Collection
	Database() *mongo.Database
	MongoClient() *mongo.Client
	CreateIndex(ctx context.Context, k interface{}, o *options.IndexOptions) (string, error)
	InsertOne(ctx context.Context, m Document, opts ...*options.InsertOneOptions) (string, error)
	InsertMany(ctx context.Context, docs []interface{}, opts ...*options.InsertManyOptions) ([]string, error)
	UpdateOne(ctx context.Context, m Document, opts ...*options.UpdateOptions) error
	UpdateManyByFilter(ctx context.Context, filter interface{}, m Document, opts ...*options.UpdateOptions) error
	UpdateMany(ctx context.Context, filter, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)
	UpsertOne(ctx context.Context, filter interface{}, update bson.M, m Document) (Document, error)
	FindAndUpdateOne(ctx context.Context, filter interface{}, update bson.M, m Document) (Document, error)
	ReplaceOne(ctx context.Context, filter interface{}, m Document, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error)
	ReplaceOneByID(ctx context.Context, recordID string, m Document, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error)
	GetOneByID(ctx context.Context, recordID string, m Document, opts ...*options.FindOneOptions) error
	GetOneByFilter(ctx context.Context, filter interface{}, m Document, opts ...*options.FindOneOptions) error
	GetManyByFilter(ctx context.Context, filter interface{}, modelBuilder func() Document, opts ...*options.FindOptions) ([]Document, error)
	FindAllByFilter(ctx context.Context, filter interface{}, docs interface{}, opts ...*options.FindOptions) error
	FindManyByFilter(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*mongo.Cursor, error)
	CountByFilter(ctx context.Context, filter interface{}) (int64, error)
	DeleteManyByFilter(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)
	DeleteOneByID(ctx context.Context, docID string) error
	DeleteAll(ctx context.Context) error
}

Storage

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL