mongoose

package module
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2024 License: MIT Imports: 13 Imported by: 0

README

MongoDB for Tinh Tinh

GitHub Release GitHub License

Description

MongoDB for Tinh Tinh

Install

go get -u github.com/tinh-tinh/mongoose

Documentation

Index

Constants

View Source
const CONNECT_MONGO core.Provide = "CONNECT_MONGO"

Variables

This section is empty.

Functions

func ForFeature

func ForFeature(models ...ModelCommon) core.Module

ForFeature creates a module which provides each model in the given list as a provider. The provider of each model is created by calling its SetConnect method with the CONNECT_MONGO provider. The name of the provider is the same as the name of the collection, but with "Model_" prefixed. The providers are exported by the module.

func ForRoot

func ForRoot(url string, db string) core.Module

ForRoot creates a module which provides a mongodb connection from a given url. The connection is exported as CONNECT_MONGO.

func GetModelName added in v1.1.1

func GetModelName(name string) core.Provide

GetModelName returns a unique name for a model provider given a struct name. The returned name is in the format "Model_<struct_name>".

func IsValidateObjectID added in v1.1.2

func IsValidateObjectID(str string) bool

func ToDoc

func ToDoc(v interface{}) (doc *bson.D, err error)

ToDoc converts an interface{} to a bson.D, suitable for use with the bson and mongo packages. If the input is nil, ToDoc returns an empty bson.D. ToDoc returns an error if the input cannot be marshaled.

func ToObjectID added in v1.1.2

func ToObjectID(str string) primitive.ObjectID

Types

type BaseSchema

type BaseSchema struct {
	ID        primitive.ObjectID `bson:"_id"`
	CreatedAt time.Time          `bson:"createdAt"`
	UpdatedAt time.Time          `bson:"updatedAt"`
}

type BaseTimestamp

type BaseTimestamp struct {
	CreatedAt time.Time `bson:"createdAt"`
	UpdatedAt time.Time `bson:"updatedAt"`
}

type Connect

type Connect struct {
	Client *mongo.Client
	Ctx    context.Context
	DB     string
}

func InjectConnect

func InjectConnect(module *core.DynamicModule) *Connect

InjectConnect injects the CONNECT_MONGO provider and returns its value as a *Connect. The CONNECT_MONGO provider is created by the ForRoot function.

func New

func New(url string, db string, loggers ...*options.LoggerOptions) *Connect

New creates a new Connect instance by establishing a connection to a MongoDB database using the provided URI. It returns a pointer to the Connect struct, which contains the MongoDB client, context, and the database name extracted from the URI. If the connection fails, the function will panic.

func (*Connect) Ping

func (c *Connect) Ping() error

Ping pings the MongoDB server to check if the connection is alive. It returns an error if the connection is not alive.

type Model

type Model[M any] struct {
	Ctx        context.Context
	Collection *mongo.Collection
	// contains filtered or unexported fields
}

func InjectModel

func InjectModel[M any](module *core.DynamicModule, name ...string) *Model[M]

InjectModel injects a model provider and returns its value as a *Model[M]. The model provider is created by the ForFeature function. The name of the provider is the same as the name of the struct, but with "Model_" prefixed.

func NewModel

func NewModel[M any](names ...string) *Model[M]

NewModel returns a new instance of Model[M] with the given connect and name name is the name of the collection in the database the returned Model[M] is used to interact with the collection in the database

func (*Model[M]) Aggregate added in v1.1.2

func (m *Model[M]) Aggregate(pipeline mongo.Pipeline) ([]bson.M, error)

func (*Model[M]) Count

func (m *Model[M]) Count(filter interface{}) (int64, error)

Count returns the number of documents that match the filter. The filter can be any type that can be marshaled to a bson.D. It converts the filter to a BSON document using ToDoc. The function then counts the number of documents that match the query and returns the count as an int64. It returns an error if there is a problem with the query or the counting operation fails.

func (*Model[M]) Create

func (m *Model[M]) Create(input *M) (*mongo.InsertOneResult, error)

Create creates a new document in the collection using the provided input. It validates the input data and inserts a new document into the collection. Returns the result of the insertion as an *mongo.InsertOneResult and any error encountered.

func (*Model[M]) CreateMany

func (m *Model[M]) CreateMany(input []*M) (*mongo.InsertManyResult, error)

CreateMany creates multiple new documents in the collection using the provided input. It validates each document data and inserts new documents into the collection. Returns the result of the insertion as an *mongo.InsertManyResult and any error encountered.

func (*Model[M]) Delete

func (m *Model[M]) Delete(filter interface{}) error

Delete deletes a single document in the collection based on the provided filter. It converts the filter to a BSON document using ToDoc. Finally, it performs the delete operation using DeleteOne. Returns an error if the delete operation fails.

func (*Model[M]) DeleteMany

func (m *Model[M]) DeleteMany(filter interface{}) error

DeleteMany deletes multiple documents in the collection based on the provided filter. It converts the filter to a BSON document using ToDoc. Finally, it performs the delete operation using DeleteMany. Returns an error if the delete operation fails.

func (*Model[M]) Find

func (m *Model[M]) Find(filter interface{}, opts ...QueriesOptions) ([]*M, error)

func (*Model[M]) FindByID

func (m *Model[M]) FindByID(id string, opt ...QueryOptions) (*M, error)

FindByID returns a single document that matches the id. The id is the "_id" field in the document. The function takes a variable number of QueryOptions, which can be used to limit, sort, skip, or project the result. If no QueryOptions are provided, the first document in the collection is returned.

FindByID returns an error if there is a problem with the query or the document cannot be decoded. If no document matches the id, the function returns nil, nil.

func (*Model[M]) FindByIDAndDelete

func (m *Model[M]) FindByIDAndDelete(id string, opt ...*options.FindOneAndDeleteOptions) (*M, error)

FindByIDAndDelete deletes a single document that matches the id and returns the deleted document. The function takes a variable number of FindOneAndDeleteOptions, which can be used to control the delete operation. If no FindOneAndDeleteOptions are provided, the first document in the collection that matches the id is deleted.

FindByIDAndDelete returns an error if there is a problem with the query or the document cannot be decoded. If no document matches the id, the function returns nil, nil.

func (*Model[M]) FindByIDAndReplace

func (m *Model[M]) FindByIDAndReplace(id string, data *M, opt ...*options.FindOneAndReplaceOptions) (*M, error)

FindByIDAndReplace replaces a single document that matches the given id with the new data. The id corresponds to the "_id" field in the document. The new data is validated and prepared for replacement using m.validData. The function takes a variable number of FindOneAndReplaceOptions, which can be used to control the replace operation. If no FindOneAndReplaceOptions are provided, the first document in the collection that matches the id is replaced.

FindByIDAndReplace returns an error if there is a problem with the query or the document cannot be decoded. If no document matches the id, the function returns nil, nil.

func (*Model[M]) FindByIDAndUpdate

func (m *Model[M]) FindByIDAndUpdate(id string, data *M, opt ...*options.FindOneAndUpdateOptions) (*M, error)

FindByIDAndUpdate updates a single document that matches the given id with the new data. The id is the "_id" field in the document. The new data is validated and prepared for update using m.validData. The function takes a variable number of FindOneAndUpdateOptions, which can be used to control the update operation. If no FindOneAndUpdateOptions are provided, the first document in the collection that matches the id is returned and updated.

FindByIDAndUpdate returns an error if there is a problem with the query or the document cannot be decoded. If no document matches the id, the function returns nil, nil.

func (*Model[M]) FindOne

func (m *Model[M]) FindOne(filter interface{}, opts ...QueryOptions) (*M, error)

func (*Model[M]) FindOneAndDelete

func (m *Model[M]) FindOneAndDelete(filter interface{}, opt ...*options.FindOneAndDeleteOptions) (*M, error)

FindOneAndDelete deletes a single document that matches the filter and returns the deleted document. The filter can be any type that can be marshaled to a bson.D. The function takes a variable number of FindOneAndDeleteOptions, which can be used to control the delete operation. If no FindOneAndDeleteOptions are provided, the first document in the collection that matches the filter is deleted.

FindOneAndDelete returns an error if there is a problem with the query or the document cannot be decoded. If no document matches the filter, the function returns nil, nil.

func (*Model[M]) FindOneAndReplace

func (m *Model[M]) FindOneAndReplace(filter interface{}, data *M, opt ...*options.FindOneAndReplaceOptions) (*M, error)

FindOneAndReplace replaces a single document that matches the filter with the new data. The filter can be any type that can be marshaled to a bson.D. The new data is validated and prepared for update using m.validData. The function takes a variable number of FindOneAndReplaceOptions, which can be used to control the replace operation. If no FindOneAndReplaceOptions are provided, the first document in the collection that matches the filter is replaced.

FindOneAndReplace returns an error if there is a problem with the query or the document cannot be decoded. If no document matches the filter, the function returns nil, nil.

func (*Model[M]) FindOneAndUpdate

func (m *Model[M]) FindOneAndUpdate(filter interface{}, data *M, opt ...*options.FindOneAndUpdateOptions) (*M, error)

FindOneAndUpdate returns a single document that matches the filter and updates it with the new data. The filter can be any type that can be marshaled to a bson.D. The new data is validated and prepared for update using m.validData. The function takes a variable number of FindOneAndUpdateOptions, which can be used to control the update operation. If no FindOneAndUpdateOptions are provided, the first document in the collection that matches the filter is returned and updated.

FindOneAndUpdate returns an error if there is a problem with the query or the document cannot be decoded. If no document matches the filter, the function returns nil, nil.

func (*Model[M]) GetName added in v1.1.1

func (m *Model[M]) GetName() string

GetName returns the name of the collection in the database

func (*Model[M]) Index added in v1.1.2

func (m *Model[M]) Index(idx bson.D, unique bool)

func (*Model[M]) Save

func (m *Model[M]) Save() error

Save saves the changes to the model in the database. If the model has no ID, InsertOne is used to insert the document. If the model has an ID, UpdateByID is used to update the existing document. The createdAt and updatedAt fields are automatically set if not present. If the model has no changes, Save does nothing. Save returns an error if the operation fails.

func (*Model[M]) Set

func (m *Model[M]) Set(data interface{})

Set sets the data of the model to the given data. It iterates over the struct fields of the given data and sets the corresponding field of the model to the value of the field. If the field is not found in the model, it is not set. If the field is not tagged with bson, the field name is used as the key. If the field is tagged with bson, the tag value is used as the key. The given data must be a struct.

func (*Model[M]) SetConnect added in v1.1.1

func (m *Model[M]) SetConnect(connect *Connect)

SetConnect sets the context and collection of the model to the given connect. It is used internally by the ForFeature function to set the connect of the model. The given connect must be a *Connect.

func (*Model[M]) SetContext added in v1.1.2

func (m *Model[M]) SetContext(ctx context.Context)

func (*Model[M]) Transaction added in v1.1.2

func (m *Model[M]) Transaction(fnc func(session mongo.SessionContext) error, opts ...*options.TransactionOptions) error

func (*Model[M]) Update

func (m *Model[M]) Update(filter interface{}, data *M) error

Update updates a single document in the collection based on the provided filter and new data. It converts the filter to a BSON document using ToDoc. The new data is validated and prepared for update using m.validData. Finally, it performs the update operation using UpdateOne with the $set operator. Returns an error if the update operation fails.

func (*Model[M]) UpdateMany

func (m *Model[M]) UpdateMany(filter interface{}, data *M) error

UpdateMany updates multiple documents in the collection based on the provided filter and new data. It converts the filter to a BSON document using ToDoc. The new data is validated and prepared for update using m.validData. Finally, it performs the update operation using UpdateMany with the $set operator. Returns an error if the update operation fails.

type ModelCommon added in v1.1.1

type ModelCommon interface {
	SetConnect(connect *Connect)
	GetName() string
}

type QueriesOptions

type QueriesOptions struct {
	Sort       bson.D
	Skip       int64
	Limit      int64
	Projection bson.D
	Ref        []string
}

type QueryOptions

type QueryOptions struct {
	Sort       bson.D
	Projection bson.D
	Ref        []string
}

type RefPath added in v1.1.2

type RefPath struct {
	From       string
	ForeignKey string
	As         string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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