elemental

package
v1.19.4 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2025 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const AuditUserFallback = "System"
View Source
const ConnectionTimeout = 30 * time.Second

The default connection timeout for elemental connections

View Source
const CtxUser = "user"
View Source
const EventDeploymentDiscovered = "DeploymentDiscovered"

Variables

View Source
var (
	ErrURIRequired               = errors.New("URI is required")
	ErrInvalidConnectionArgument = errors.New("invalid connection argument")
	ErrMustPairSortArguments     = errors.New("sort arguments must be in pairs")
)
View Source
var Array = reflect.Array
View Source
var AuditModel = NewModel[Audit]("Audit", NewSchema(map[string]Field{
	"Entity": {
		Type:     reflect.String,
		Required: true,
	},
	"Type": {
		Type: reflect.String,
	},
	"Document": {
		Type:     reflect.Map,
		Required: true,
	},
	"User": {
		Type: reflect.String,
	},
}, SchemaOptions{
	Collection:              "audits",
	BypassSchemaEnforcement: true,
}))
View Source
var Bool = reflect.Bool
View Source
var BoolMap = reflect.TypeOf(map[string]bool{})
View Source
var BoolSlice = reflect.TypeOf([]bool{})
View Source
var Float32 = reflect.Float32
View Source
var Float32Map = reflect.TypeOf(map[string]float32{})
View Source
var Float32Slice = reflect.TypeOf([]float32{})
View Source
var Float64 = reflect.Float64
View Source
var Float64Map = reflect.TypeOf(map[string]float64{})
View Source
var Float64Slice = reflect.TypeOf([]float64{})
View Source
var GetClient = GetConnection

Same as 'GetConnection' method

View Source
var Int = reflect.Int
View Source
var Int32 = reflect.Int32
View Source
var Int32Map = reflect.TypeOf(map[string]int32{})
View Source
var Int32Slice = reflect.TypeOf([]int32{})
View Source
var Int64 = reflect.Int64
View Source
var Int64Map = reflect.TypeOf(map[string]int64{})
View Source
var Int64Slice = reflect.TypeOf([]int64{})
View Source
var IntMap = reflect.TypeOf(map[string]int{})
View Source
var IntSlice = reflect.TypeOf([]int{})
View Source
var Interface = reflect.Interface
View Source
var Map = reflect.Map
View Source
var Models = make(map[string]any)

Static map of all created models. You can use this map to access models by name. The key is the name of the model and the value is the model itself.

View Source
var NativeModel = NewModel[map[string]any]("ElementalNativeModel", NewSchema(map[string]Field{}))

A Predefined model with type map[string]any which can be used to access the Elemental APIs if you don't want to define a schema.

View Source
var ObjectIDSlice = reflect.TypeOf([]primitive.ObjectID{})
View Source
var Slice = reflect.Slice
View Source
var String = reflect.String
View Source
var StringMap = reflect.TypeOf(map[string]string{})
View Source
var StringSlice = reflect.TypeOf([]string{})
View Source
var Struct = reflect.Struct
View Source
var Uint = reflect.Uint
View Source
var Uint32 = reflect.Uint32
View Source
var Uint32Map = reflect.TypeOf(map[string]uint32{})
View Source
var Uint32Slice = reflect.TypeOf([]uint32{})
View Source
var Uint64 = reflect.Uint64
View Source
var Uint64Map = reflect.TypeOf(map[string]uint64{})
View Source
var Uint64Slice = reflect.TypeOf([]uint64{})
View Source
var UintMap = reflect.TypeOf(map[string]uint{})
View Source
var UintSlice = reflect.TypeOf([]uint{})

Functions

func ClientTransaction

func ClientTransaction(alias string, fn func(ctx mongo.SessionContext) (any, error)) (any, error)

Essentially the same as Transaction, but with an alias which points to the connection to use

func Connect added in v1.7.0

func Connect(arg any) mongo.Client

Connect to a new data source.

@param arg - The connection string or ConnectionOptions struct

Example:

	client1 := Connect("mongodb://localhost:27017")
    // or
	client2 := Connect(ConnectionOptions{
		Alias: "secondary",
		URI: "mongodb://localhost:27018",
		ClientOptions: options.Client().SetMaxPoolSize(10),
	})

func Disconnect added in v1.7.0

func Disconnect(aliases ...string) error

Disconnect a set of connections by alias or disconnect all connections if no alias is provided

@param aliases - The aliases of the connections to disconnect

func DropAllDatabases added in v1.7.0

func DropAllDatabases(alias ...string)

Drops all databases across a given client or all clients if no alias is provided

func GetConnection added in v1.7.0

func GetConnection(alias ...string) *mongo.Client

Get the database connection for a given alias or the default connection if no alias is provided

@param alias - The alias of the connection to get

func OnConnectionEvent added in v1.7.0

func OnConnectionEvent(event string, handler func(), alias ...string)

Add a listener to a connection event

@param event - The event to listen for. From the default mongo driver event package or from elemental

@param handler - The function to call when the event is triggered

@param alias - The alias of the connection to listen to

func Ping added in v1.10.0

func Ping(alias ...string) error

Pings the primary server of a given connection or the default connection if no alias is provided This will timeout after 5 seconds

func RemoveConnectionEvent added in v1.7.0

func RemoveConnectionEvent(event string, alias ...string)

Remove a listener from a connection event

@param event - The event to remove the listener from

@param alias - The alias of the connection to remove the listener from

func Transaction

func Transaction(fn func(ctx mongo.SessionContext) (any, error)) (any, error)

Run a transaction with the given function. This is the simplest form of a transaction which uses the default connection and takes care of session management

func TransactionBatch added in v1.1.0

func TransactionBatch(queries ...ModelInterface[any]) ([]any, []any)

TransactionBatch runs a batch of queries in a transaction. If any of the queries fail, the transaction is aborted and all changes are rolled back. It returns a slice of results and a slice of errors. The results are in the same order as the queries, and the errors are in the same order as the results.

func UseDatabase added in v1.7.0

func UseDatabase(database string, alias ...string) *mongo.Database

UseDatabase a specific database on a connection

@param database - The name of the database to use

@param alias - The alias of the connection to use

func UseDefaultDatabase added in v1.7.0

func UseDefaultDatabase(alias ...string) *mongo.Database

Use the default database on a connection. Uses the default connection if no alias is provided

@param alias - The alias of the connection to use

Types

type Audit

type Audit struct {
	Entity    string      `json:"entity" bson:"entity"`         // The name of the model that was audited.
	Type      AuditType   `json:"type" bson:"type"`             // The type of operation that was performed (insert, update, delete).
	Document  primitive.M `json:"document" bson:"document"`     // The document that was affected by the operation.
	User      string      `json:"user" bson:"user"`             // The user who performed the operation if available within the context.
	CreatedAt time.Time   `json:"created_at" bson:"created_at"` // The date and time when the operation was performed.
}

type AuditType

type AuditType string
const (
	AuditTypeInsert AuditType = "insert"
	AuditTypeUpdate AuditType = "update"
	AuditTypeDelete AuditType = "delete"
)

type CollectionStats

type CollectionStats struct {
	NS                 string         `bson:"ns" json:"ns"`
	Size               int64          `bson:"size" json:"size"`
	Capped             bool           `bson:"capped" json:"capped"`
	Count              int64          `bson:"count" json:"count"`
	AvgObjSize         int64          `bson:"avgObjSize" json:"avgObjSize"`
	FreeStorageSize    int64          `bson:"freeStorageSize" json:"freeStorageSize"`
	StorageSize        int64          `bson:"storageSize" json:"storageSize"`
	IndexBuilds        []string       `bson:"indexBuilds" json:"indexBuilds"`
	IndexSizes         map[string]int `bson:"indexSizes" json:"indexSizes"`
	TotalIndexSize     int64          `bson:"totalIndexSize" json:"totalIndexSize"`
	NumberOfIndexes    int64          `bson:"nindexes" json:"nindexes"`
	NumberOfOrphanDocs int64          `bson:"numOrphanDocs" json:"numOrphanDocs"`
	OK                 int64          `bson:"ok" json:"ok"`
	OperationTime      time.Time      `bson:"operationTime" json:"operationTime"`
	ReadOnly           bool           `bson:"readOnly" json:"readOnly"`
	ReadPreference     ReadPreference `bson:"readPreference" json:"readPreference"`
	RejectedPlans      []string       `bson:"rejectedPlans" json:"rejectedPlans"`
	ServerInfo         ServerInfo     `bson:"serverInfo" json:"serverInfo"`
	ShardIdentity      ShardIdentity  `bson:"shardIdentity" json:"shardIdentity"`
	Shards             []Shard        `bson:"shards" json:"shards"`
	UserFlags          int64          `bson:"userFlags" json:"userFlags"`
	UserFlagsData      UserFlagsData  `bson:"userFlagsData" json:"userFlagsData"`
	WriteConcern       WriteConcern   `bson:"writeConcern" json:"writeConcern"`
}

type ConnectionOptions added in v1.7.0

type ConnectionOptions struct {
	Alias         string                 // The alias of the connection, if not provided, it will be set to "default"
	URI           string                 // The connection string to connect to the database
	ClientOptions *options.ClientOptions // The options to use when creating the client
	PoolMonitor   *event.PoolMonitor     // The underlying event pool monitor to use when creating the client
}

Elemental connection options

type Field

type Field struct {
	Type       FieldType             // Type of the field. Can be of reflect.Kind, reflect.Type, an Elemental alias such as elemental.String or a custom reflection
	Schema     *Schema               // Defines a subschema for the field if it is a subdocument
	Required   bool                  // Whether the field is required or not when creating a new document
	Default    any                   // Default value for the field when creating a new document
	Min        float64               // Minimum value for the field when it is a number
	Max        float64               // Maximum value for the field when it is a number
	Length     int64                 // Maximum length for the field when it is a string
	Regex      *regexp.Regexp        // A regex pattern that the field must match when it is a string
	Index      *options.IndexOptions // Raw driver index options for the field. Can be used to create unique indexes, sparse indexes, etc.
	IndexOrder int                   // Sort order for the index. 1 for ascending, -1 for descending
	Ref        string                // Reference to another model if the field is a reference
	Collection string                // Collection name if the field is a reference
	IsRefID    bool                  // In development for cluster mode, don't use it yet
}

type FieldType added in v1.19.0

type FieldType interface {
	String() string
}

type Model

type Model[T any] struct {
	Name   string // The name of the model
	Schema Schema // The underlying schema used by this model
	Cloned bool   // Indicates if this model has been cloned at least once
	// contains filtered or unexported fields
}

func NewModel

func NewModel[T any](name string, schema Schema) Model[T]

NewModel creates a new model with the given name and schema. If a model with the same name already exists, it will return the existing model.

func (Model[T]) AddToSet

func (m Model[T]) AddToSet(field string, values ...any) Model[T]

Extends the query to add the given values to the set of values for the given field if they are not already present

func (Model[T]) AvgObjSize

func (m Model[T]) AvgObjSize(ctx ...context.Context) int64

The average size of each document in the collection

func (Model[T]) Between

func (m Model[T]) Between(minimum, maximum any) Model[T]

Extends the query to return only documents that are between the given values.

func (Model[T]) Client added in v1.8.1

func (m Model[T]) Client() *mongo.Client

Returns the underlying client instance this model uses This method is an alias for Connection() and is kept for clarity to indicate that this retrieves a client instance

func (Model[T]) Clone added in v1.2.0

func (m Model[T]) Clone() Model[T]

Creates a clone of the current model with the same query pipeline and options as has been set on the current model. Invoking this method will set the Cloned flag of the newly created model to true.

func (Model[T]) Collection

func (m Model[T]) Collection() *mongo.Collection

Returns the underlying collection instance this model uses.

func (Model[T]) Connection added in v1.2.0

func (m Model[T]) Connection() *mongo.Client

Returns the underlying client instance this model uses

func (Model[T]) CountDocuments

func (m Model[T]) CountDocuments(query ...primitive.M) Model[T]

Extends the query with a count stage to count the number of documents in the collection. It optionally accepts one or more queries to filter the results before counting. If multiple queries are provided, they are merged into a single from left to right.

func (Model[T]) Create

func (m Model[T]) Create(doc T) Model[T]

Extends the query to insert a single document into the collection. This method validates the document against the model schema and panics if any errors are found.

func (Model[T]) CreateCollection

func (m Model[T]) CreateCollection(ctx ...context.Context) *mongo.Collection

Creates the collection used by this model. This method will only create the collection if it does not exist. This will happen automatically when the model is created, so you most likely won't need to call this method manually.

func (Model[T]) CreateMany

func (m Model[T]) CreateMany(docs []T) Model[T]

Extends the query to insert multiple documents into the collection. This method is an alias for InsertMany and is provided for convenience.

func (Model[T]) CurrentDate

func (m Model[T]) CurrentDate(field string) Model[T]

Extends the query to set the value of the given field to the current date

func (Model[T]) Database

func (m Model[T]) Database() *mongo.Database

Returns the underlying database instance this model uses

func (Model[T]) Dec

func (m Model[T]) Dec(field string, value int) Model[T]

Extends the query with a decrement operation matching the given field

func (Model[T]) Delete

func (m Model[T]) Delete(doc T) Model[T]

Extends the query with a delete operation matching the given document. If the model has soft delete enabled, it will update the document with a deleted_at field instead of deleting it.

func (Model[T]) DeleteByID

func (m Model[T]) DeleteByID(id any) Model[T]

Extends the query with a delete operation matching the given id. It deletes only the first document that matches the id. This method will not return the deleted document. If the model has soft delete enabled, it will update the document with a deleted_at field instead of deleting it. The id can be a string or an ObjectID.

func (Model[T]) DeleteMany

func (m Model[T]) DeleteMany(query ...primitive.M) Model[T]

Extends the query with a delete operation matching the given query(s) If multiple queries are provided, they are merged into a single from left to right. It deletes all documents that match the query. This method will not return the deleted documents. If the model has soft delete enabled, it will update the documents with a deleted_at field instead of deleting them.

func (Model[T]) DeleteOne

func (m Model[T]) DeleteOne(query ...primitive.M) Model[T]

Extends the query with a delete operation matching the given query(s). If multiple queries are provided, they are merged into a single from left to right. It deletes only the first document that matches the query. This method will not return the deleted document. If the model has soft delete enabled, it will update the document with a deleted_at field instead of deleting it.

func (*Model[T]) DisableSoftDelete added in v1.8.0

func (m *Model[T]) DisableSoftDelete()

Disables soft delete for the model.

func (Model[T]) Distinct

func (m Model[T]) Distinct(field string, query ...primitive.M) Model[T]

Distinct returns a list of distinct values for the given field. It optionally accepts one or more queries to filter the results before getting the distinct values. If multiple queries are provided, they are merged into a single from left to right.

func (Model[T]) Div

func (m Model[T]) Div(field string, value int) Model[T]

Extends the query with a division operation matching the given field

func (Model[T]) Drop

func (m Model[T]) Drop(ctx ...context.Context)

Drops the collection used by this model.

func (Model[T]) DropIndex added in v1.8.0

func (m Model[T]) DropIndex(indexName string, ctx ...context.Context) (bson.Raw, error)

Drops a specific index for this model.

func (Model[T]) DropIndexes

func (m Model[T]) DropIndexes(ctx ...context.Context) (bson.Raw, error)

Drops all indexes for this model except the default `_id` index.

func (Model[T]) ElementMatches

func (m Model[T]) ElementMatches(query primitive.M) Model[T]

Extends the query to return only documents where the given field is an array and has an element that matches the given query.

func (Model[T]) EnableAuditing

func (m Model[T]) EnableAuditing(ctx ...context.Context)

Enables auditing for the current model.

func (*Model[T]) EnableSoftDelete added in v0.0.7

func (m *Model[T]) EnableSoftDelete(deletedAtFieldName ...string)

Enables soft delete for the model.

func (Model[T]) Equals

func (m Model[T]) Equals(value any) Model[T]

Extends the query to return only documents that equal the given value.

func (Model[T]) EstimatedDocumentCount

func (m Model[T]) EstimatedDocumentCount(ctx ...context.Context) int64

Returns the count of all documents in a collection or view

func (Model[T]) Exec

func (m Model[T]) Exec(ctx ...context.Context) any

Exec is the final step in the query builder chain. It executes the query and returns the results. The result of this method is not type safe, so you need to cast it to the expected type.

func (Model[T]) ExecInt added in v1.8.0

func (m Model[T]) ExecInt(ctx ...context.Context) int

ExecInt is a convenience method that executes the query and returns the first result as an int. It is a type safe method, so you don't need to cast the result. If the query returns nothing it will return 0. This method is useful for queries that return a single integer value, such as count queries or schedule queries which return a cron entry ID.

func (Model[T]) ExecInto added in v1.19.0

func (m Model[T]) ExecInto(result any, ctx ...context.Context)

ExecInto is a specialized method that executes the query and unmarshals the result into the provided result variable. It is useful when you want to extract results into a custom struct other than the model type such as when you populate certain fields.

The result variable must be a pointer to your desired type.

func (Model[T]) ExecPtr added in v1.8.0

func (m Model[T]) ExecPtr(ctx ...context.Context) *T

ExecPtr is a convenience method that executes the query and returns the first result as a pointer. It is a type safe method, so you don't need to cast the result. If the query returns nothing it will return nil.

func (Model[T]) ExecSS added in v1.14.5

func (m Model[T]) ExecSS(ctx ...context.Context) []string

ExecSS is a convenience method that executes the query and returns the first result as a slice of strings. It is a type safe method, so you don't need to cast the result. If the query returns nothing it will return an empty slice. This method is useful for queries that return an array of strings, such as distinct queries.

func (Model[T]) ExecT added in v1.3.0

func (m Model[T]) ExecT(ctx ...context.Context) T

ExecT is a convenience method that executes the query and returns the first result. It is a type safe method, so you don't need to cast the result. If the query returns nothing it will return the zero value of the type.

func (Model[T]) ExecTP added in v1.14.1

func (m Model[T]) ExecTP(ctx ...context.Context) PaginateResult[T]

ExecTP is a convenience method that executes the query and returns the results as a PaginateResult. It is a type safe method, so you don't need to cast the result. If the query returns nothing, it will return an empty PaginateResult. This method is useful for pagination queries.

func (Model[T]) ExecTT added in v1.8.0

func (m Model[T]) ExecTT(ctx ...context.Context) []T

ExecTT is a convenience method that executes the query and returns the results as a slice. It is a type safe method, so you don't need to cast the result. If the query returns nothing it will return an empty slice.

func (Model[T]) Exists

func (m Model[T]) Exists(value bool) Model[T]

Extends the query to return only documents where the given field exists.

func (Model[T]) Find

func (m Model[T]) Find(query ...primitive.M) Model[T]

Extends the query with a match stage to find multiple documents in the collection. Optionally accepts one or more queries to filter the results. If multiple queries are provided, they are merged into a single from left to right.

func (Model[T]) FindByID

func (m Model[T]) FindByID(id any) Model[T]

Extends the query with a match stage to find a document by its ID. The id can be a string or an ObjectID.

func (Model[T]) FindByIDAndDelete added in v1.12.0

func (m Model[T]) FindByIDAndDelete(id any) Model[T]

Extends the query with a delete operation matching the given id It deletes only the first document that matches the id. This method will return the deleted document. If the model has soft delete enabled, it will update the document with a deleted_at field instead of deleting it. The id can be a string or an ObjectID.

func (Model[T]) FindByIDAndReplace

func (m Model[T]) FindByIDAndReplace(id any, doc any, opts ...*options.FindOneAndReplaceOptions) Model[T]

Extends the query with a replace operation matching the given id This method will return the replaced document. The id can be a string or an ObjectID.

func (Model[T]) FindByIDAndUpdate

func (m Model[T]) FindByIDAndUpdate(id any, doc any, opts ...*options.FindOneAndUpdateOptions) Model[T]

Extends the query with an update operation matching the given id The id can be a string or an ObjectID.

func (Model[T]) FindOne

func (m Model[T]) FindOne(query ...primitive.M) Model[T]

Extends the query with a limit stage to find a single document. It optionally accepts one or more queries to filter the results before limiting. If multiple queries are provided, they are merged into a single from left to right.

func (Model[T]) FindOneAndDelete

func (m Model[T]) FindOneAndDelete(query ...primitive.M) Model[T]

Extends the query with a delete operation matching the given query(s) If multiple queries are provided, they are merged into a single from left to right. It deletes only the first document that matches the query. This method will return the deleted document. If the model has soft delete enabled, it will update the document with a deleted_at field instead of deleting it.

func (Model[T]) FindOneAndReplace

func (m Model[T]) FindOneAndReplace(query *primitive.M, doc any, opts ...*options.FindOneAndReplaceOptions) Model[T]

Extends the query with a replace operation matching the given query(s) If multiple queries are provided, they are merged into a single from left to right. It replaces only the first document that matches the query.

func (Model[T]) FindOneAndUpdate

func (m Model[T]) FindOneAndUpdate(query *primitive.M, doc any, opts ...*options.FindOneAndUpdateOptions) Model[T]

Extends the query with an update operation matching the given query(s) If multiple queries are provided, they are merged into a single from left to right. It updates only the first document that matches the query.

func (Model[T]) GreaterThan

func (m Model[T]) GreaterThan(value any) Model[T]

Extends the query to return only documents that are greater than the given value.

func (Model[T]) GreaterThanOrEquals

func (m Model[T]) GreaterThanOrEquals(value any) Model[T]

Extends the query to return only documents that are greater than or equal to the given value.

func (Model[T]) Has

func (m Model[T]) Has(value string) Model[T]

Extends the query to return only documents where the given field is an array and has an element that matches the given value. This is a shorthand for ElementMatches with an equality operator.

func (Model[T]) In

func (m Model[T]) In(values ...any) Model[T]

Extends the query to return only documents where the given field has a value equal to any of the given values.

func (Model[T]) Inc

func (m Model[T]) Inc(field string, value int) Model[T]

Extends the query with an increment operation matching the given field

func (Model[T]) InsertMany

func (m Model[T]) InsertMany(docs []T) Model[T]

Extends the query to insert multiple documents into the collection. This method validates the document against the model schema and panics if any errors are found.

func (Model[T]) InvalidateTriggers added in v1.14.3

func (m Model[T]) InvalidateTriggers()

InvalidateTriggers clears all triggers for the model. This includes audits.

func (Model[T]) IsArray

func (m Model[T]) IsArray() Model[T]

func (Model[T]) IsBinary

func (m Model[T]) IsBinary() Model[T]

func (Model[T]) IsBoolean

func (m Model[T]) IsBoolean() Model[T]

func (Model[T]) IsCapped

func (m Model[T]) IsCapped(ctx ...context.Context) bool

Returns true if the model collection is a capped collection, otherwise returns false

func (Model[T]) IsCodeWithScope

func (m Model[T]) IsCodeWithScope() Model[T]

func (Model[T]) IsDBPointer

func (m Model[T]) IsDBPointer() Model[T]

func (Model[T]) IsDateTime

func (m Model[T]) IsDateTime() Model[T]

func (Model[T]) IsDecimal128

func (m Model[T]) IsDecimal128() Model[T]

func (Model[T]) IsDouble

func (m Model[T]) IsDouble() Model[T]

func (Model[T]) IsInt32

func (m Model[T]) IsInt32() Model[T]

func (Model[T]) IsInt64

func (m Model[T]) IsInt64() Model[T]

func (Model[T]) IsJavaScript

func (m Model[T]) IsJavaScript() Model[T]

func (Model[T]) IsNull

func (m Model[T]) IsNull() Model[T]

func (Model[T]) IsObjectID

func (m Model[T]) IsObjectID() Model[T]

func (Model[T]) IsRegex

func (m Model[T]) IsRegex() Model[T]

func (Model[T]) IsString

func (m Model[T]) IsString() Model[T]

func (Model[T]) IsSymbol

func (m Model[T]) IsSymbol() Model[T]

func (Model[T]) IsTimestamp

func (m Model[T]) IsTimestamp() Model[T]

func (Model[T]) IsType

func (m Model[T]) IsType(value bsontype.Type) Model[T]

func (Model[T]) IsUndefined

func (m Model[T]) IsUndefined() Model[T]

func (Model[T]) LessThan

func (m Model[T]) LessThan(value any) Model[T]

Extends the query to return only documents that are less than the given value.

func (Model[T]) LessThanOrEquals

func (m Model[T]) LessThanOrEquals(value any) Model[T]

Extends the query to return only documents that are less than or equal to the given value.

func (Model[T]) Limit

func (m Model[T]) Limit(limit int64) Model[T]

Limits the number of documents returned by the query.

func (Model[T]) Max

func (m Model[T]) Max(field string, value int) Model[T]

Extends the query to update the value of the given field if the given value is greater than the current value

func (Model[T]) Min

func (m Model[T]) Min(field string, value int) Model[T]

Extends the query to update the value of the given field if the given value is less than the current value

func (Model[T]) Mod

func (m Model[T]) Mod(divisor, remainder int) Model[T]

Extends the query to return only documents where the value of a field divided by a divisor is equal to the given remainder.

func (Model[T]) Mul

func (m Model[T]) Mul(field string, value int) Model[T]

Extends the query with a multiplication operation matching the given field

func (Model[T]) New

func (m Model[T]) New() Model[T]

Signals the query to return the new document instead of the original document after an update

func (Model[T]) NotEquals

func (m Model[T]) NotEquals(value any) Model[T]

Extends the query to return only documents that do not equal the given value.

func (Model[T]) NotIn

func (m Model[T]) NotIn(values ...any) Model[T]

Extends the query to return only documents where the given field does not have any of the given values.

func (Model[T]) NumberOfIndexes

func (m Model[T]) NumberOfIndexes(ctx ...context.Context) int64

Returns the number of indexes in the model collection

func (Model[T]) OnCollectionDrop

func (m Model[T]) OnCollectionDrop(f func(), opts ...TriggerOptions) *mongo.ChangeStream

Listens for collection drop events and calls the provided function. For more information, refer the following link: https://www.mongodb.com/docs/manual/reference/change-events/drop

func (Model[T]) OnCollectionRename

func (m Model[T]) OnCollectionRename(f func(), opts ...TriggerOptions) *mongo.ChangeStream

Listens for collection rename events and calls the provided function. For more information, refer the following link: https://www.mongodb.com/docs/manual/reference/change-events/rename

func (Model[T]) OnDelete

func (m Model[T]) OnDelete(f func(id primitive.ObjectID), opts ...TriggerOptions) *mongo.ChangeStream

Listens for delete events on the collection and calls the provided function with the deleted document's ID. For more information, refer the following link: https://www.mongodb.com/docs/manual/reference/change-events/delete

func (Model[T]) OnInsert

func (m Model[T]) OnInsert(f func(doc T), opts ...TriggerOptions) *mongo.ChangeStream

Listens for insert events on the collection and calls the provided function with the inserted document. For more information, refer the following link: https://www.mongodb.com/docs/manual/reference/change-events/insert

func (Model[T]) OnReplace

func (m Model[T]) OnReplace(f func(doc T), opts ...TriggerOptions) *mongo.ChangeStream

Listens for replace events on the collection and calls the provided function with the replaced document. For more information, refer the following link: https://www.mongodb.com/docs/manual/reference/change-events/replace

func (Model[T]) OnStreamInvalidate

func (m Model[T]) OnStreamInvalidate(f func(), opts ...TriggerOptions) *mongo.ChangeStream

Listens for stream invalidation events and calls the provided function. For more information, refer the following link: https://www.mongodb.com/docs/manual/reference/change-events/invalidate

func (Model[T]) OnUpdate

func (m Model[T]) OnUpdate(f func(doc T), opts ...TriggerOptions) *mongo.ChangeStream

Listens for update events on the collection and calls the provided function with the updated document. For more information, refer the following link: https://www.mongodb.com/docs/manual/reference/change-events/update

func (Model[T]) Or

func (m Model[T]) Or() Model[T]

Extends the query with an "or" condition.

func (Model[T]) OrFail

func (m Model[T]) OrFail(err ...error) Model[T]

Instructs a query to panic if no results are found matching the given query. It optionally accepts a custom error to panic with. If no error is provided, it will panic with a default error message.

func (Model[T]) OrWhere

func (m Model[T]) OrWhere(field string, equals ...any) Model[T]

Extends the query with an or where clause. The value of the clause if specified within this method itself will function as an equals clause. If you want to use a different operator, you can use the OrWhere method and chain it with another operator method.

func (Model[T]) Paginate

func (m Model[T]) Paginate(page, limit int64) Model[T]

Paginate the results of the query. It adds a $facet stage to the pipeline to get both the documents and the total count. The final result of the query will be a PaginateResult[T] struct containing the documents, total count, current page, limit, total pages, and next/previous page information.

func (Model[T]) Ping

func (m Model[T]) Ping(ctx ...context.Context) error

Sends out a ping to the underlying client connection used by this model.

func (Model[T]) Pop

func (m Model[T]) Pop(field string, value ...int) Model[T]

Extends the query to remove the last element from the array of the given field

func (Model[T]) Populate

func (m Model[T]) Populate(values ...any) Model[T]

Finds and attaches the referenced documents to the main document returned by the query. The fields to populate must have a 'Collection' or 'Ref' property in their schema definition.

It can accept a single string, a slice of strings, or a map with 'path' and optionally a 'select' or a 'pipeline' key.

func (Model[T]) PostDeleteMany

func (m Model[T]) PostDeleteMany(f func(result *mongo.DeleteResult, err error) bool)

func (Model[T]) PostDeleteOne

func (m Model[T]) PostDeleteOne(f func(result *mongo.DeleteResult, err error) bool)

func (Model[T]) PostFind

func (m Model[T]) PostFind(f func(doc *[]T) bool)

func (Model[T]) PostFindOneAndDelete

func (m Model[T]) PostFindOneAndDelete(f func(doc *T) bool)

func (Model[T]) PostFindOneAndReplace

func (m Model[T]) PostFindOneAndReplace(f func(doc *T) bool)

func (Model[T]) PostFindOneAndUpdate

func (m Model[T]) PostFindOneAndUpdate(f func(doc *T) bool)

func (Model[T]) PostSave

func (m Model[T]) PostSave(f func(doc *bson.M) bool)

func (Model[T]) PostUpdateOne

func (m Model[T]) PostUpdateOne(f func(result *mongo.UpdateResult, err error) bool)

func (Model[T]) PreDeleteMany

func (m Model[T]) PreDeleteMany(f func(filters *primitive.M) bool)

func (Model[T]) PreDeleteOne

func (m Model[T]) PreDeleteOne(f func(filters *primitive.M) bool)

func (Model[T]) PreFindOneAndDelete

func (m Model[T]) PreFindOneAndDelete(f func(filters *primitive.M) bool)

func (Model[T]) PreFindOneAndReplace added in v1.19.0

func (m Model[T]) PreFindOneAndReplace(f func(filters *primitive.M, doc any) bool)

func (Model[T]) PreFindOneAndUpdate

func (m Model[T]) PreFindOneAndUpdate(f func(filters *primitive.M, doc any) bool)

func (Model[T]) PreSave

func (m Model[T]) PreSave(f func(doc *bson.M) bool)

func (Model[T]) PreUpdateOne

func (m Model[T]) PreUpdateOne(f func(doc any) bool)

func (Model[T]) Pull

func (m Model[T]) Pull(field string, value any) Model[T]

Extends the query to remove all elements from the array of the given field where the value is equal to the given value

func (Model[T]) PullAll

func (m Model[T]) PullAll(field string, values ...any) Model[T]

Extends the query to remove all elements from the array of the given field where the value is equal to any of the given values

func (Model[T]) Push

func (m Model[T]) Push(field string, values ...any) Model[T]

Extends the query to add the given values to the array of the given field

func (Model[T]) QS

func (m Model[T]) QS(query string) Model[T]

QS allows you to construct an Elemental query directly from a request's query string.

It uses the filterquery plugin to parse the query string and apply filters, sorting, lookups, and projections to the final query.

Usage:

UserModel.QS("filter[name]=John&sort[name]=asc&include=field1&select=field1").ExecTT()

func (Model[T]) QSR added in v1.14.0

func (m Model[T]) QSR(result fq.Result) Model[T]

QSR allows you to construct an Elemental query directly from a FilterQueryResult.

Usage:

UserModel.QSR(fq.Parse("filter[name]=John&sort[name]=asc&include=field1&select=field1")).ExecTT()

func (Model[T]) Regex

func (m Model[T]) Regex(pattern string, options ...string) Model[T]

Extends the query to return only documents that match the given regular expression. It optionaly accepts options for the regex, such as "i" for case-insensitive matching.

func (Model[T]) Rename

func (m Model[T]) Rename(field string, newField string) Model[T]

Extends the query to update the name of the given field

func (Model[T]) ReplaceByID

func (m Model[T]) ReplaceByID(id any, doc any, opts ...*options.ReplaceOptions) Model[T]

Extends the query with a replace operation matching the given id The id can be a string or an ObjectID.

func (Model[T]) ReplaceOne

func (m Model[T]) ReplaceOne(query *primitive.M, doc any, opts ...*options.ReplaceOptions) Model[T]

Extends the query with a replace operation matching the given query(s) If multiple queries are provided, they are merged into a single from left to right. It replaces only the first document that matches the query.

func (Model[T]) Save

func (m Model[T]) Save(doc T) Model[T]

Extends the query with an upsert operation matching the id of the given document

func (Model[T]) Schedule

func (m Model[T]) Schedule(spec string, onExecutionError ...func(any)) Model[T]

Marks this query to be executed on a given schedule. For the schedule format, see https://pkg.go.dev/github.com/robfig/cron/v3#hdr-CRON_Expression_Format Optionally accepts a function to be called on an execution error/panic.

func (Model[T]) Select

func (m Model[T]) Select(fields ...any) Model[T]

Extends the query with a projection stage. The projection stage is used to specify which fields to include or exclude from the results.

func (Model[T]) Set

func (m Model[T]) Set(doc any) Model[T]

func (Model[T]) SetCollection

func (m Model[T]) SetCollection(collection string) Model[T]

Sets a temporary collection for this model. This collection will be used for the next operation only.

func (Model[T]) SetConnection

func (m Model[T]) SetConnection(connection string) Model[T]

Sets a temporary connection for this model. This connection will be used for the next operation only.

func (Model[T]) SetDatabase

func (m Model[T]) SetDatabase(database string) Model[T]

Sets a temporary database for this model. This database will be used for the next operation only.

func (Model[T]) Shift

func (m Model[T]) Shift(field string) Model[T]

Extends the query to remove the first element from the array of the given field

func (Model[T]) Size

func (m Model[T]) Size(value int) Model[T]

Extends the query to return only documents where the given field is an array and has a size equal to the given value.

func (Model[T]) Skip

func (m Model[T]) Skip(skip int64) Model[T]

Skips the first n documents in the query result.

func (Model[T]) Sort

func (m Model[T]) Sort(args ...any) Model[T]

Extends the query with a sort stage. The sort stage is used to specify the order in which the results should be returned.

func (Model[T]) Stats

func (m Model[T]) Stats(ctx ...context.Context) CollectionStats

Returns statistics about the model collection

func (Model[T]) StorageSize

func (m Model[T]) StorageSize(ctx ...context.Context) int64

The total amount of storage in bytes allocated to this collection for document storage

func (Model[T]) SyncIndexes

func (m Model[T]) SyncIndexes(ctx ...context.Context)

Creates or updates the indexes for this model. This method will only create the indexes if they do not exist.

func (Model[T]) TotalIndexSize

func (m Model[T]) TotalIndexSize(ctx ...context.Context) int64

The total size of all indexes for the collection

func (Model[T]) TotalSize

func (m Model[T]) TotalSize(ctx ...context.Context) int64

The total size in bytes of the data in the collection plus the size of every index on the collection

func (Model[T]) Unschedule

func (m Model[T]) Unschedule(id int)

Unschedule a query that was previously scheduled.

func (Model[T]) UnscheduleAll

func (m Model[T]) UnscheduleAll()

Unschedule all queries that were previously scheduled.

func (Model[T]) Unset

func (m Model[T]) Unset(doc any) Model[T]

func (Model[T]) UpdateByID

func (m Model[T]) UpdateByID(id any, doc any, opts ...*options.UpdateOptions) Model[T]

Extends the query with an update operation matching the given id It updates only the first document that matches the id. The id can be a string or an ObjectID.

func (Model[T]) UpdateMany

func (m Model[T]) UpdateMany(query *primitive.M, doc any, opts ...*options.UpdateOptions) Model[T]

Extends the query with an update operation matching the given query(s) If multiple queries are provided, they are merged into a single from left to right. It updates all documents that match the query.

func (Model[T]) UpdateOne

func (m Model[T]) UpdateOne(query *primitive.M, doc any, opts ...*options.UpdateOptions) Model[T]

Extends the query with an update operation matching the given query(s) If multiple queries are provided, they are merged into a single from left to right. It updates only the first document that matches the query.

func (Model[T]) Upsert

func (m Model[T]) Upsert() Model[T]

Signals the query to insert a new document if no documents match the query

func (Model[T]) Validate

func (m Model[T]) Validate(doc T)

Validates a document against the model schema. This method will panic if any errors are found. This is the method being called when a new document is inserted.

func (Model[T]) Where

func (m Model[T]) Where(field string, equals ...any) Model[T]

Extends the query with a where clause. The value of the clause if specified within this method itself will function as an equals clause. If you want to use a different operator, you can use the Where method and chain it with another operator method.

type ModelInterface added in v1.2.0

type ModelInterface[T any] interface {
	Exec(ctx ...context.Context) any
	Connection() *mongo.Client
}

type PaginateResult

type PaginateResult[T any] struct {
	Docs       []T    `json:"docs"`       // The documents returned by the query
	TotalDocs  int64  `json:"totalDocs"`  // The total number of documents which match the query before pagination
	Page       int64  `json:"page"`       // The current page number
	Limit      int64  `json:"limit"`      // The number of documents per page
	TotalPages int64  `json:"totalPages"` // The total number of pages which match the query
	NextPage   *int64 `json:"nextPage"`   // The next page number if there is one
	PrevPage   *int64 `json:"prevPage"`   // The previous page number if there is one
	HasPrev    bool   `json:"hasPrev"`    // Whether there is a previous page or not
	HasNext    bool   `json:"hasNext"`    // Whether there is a next page or not
}

type ReadPreference

type ReadPreference struct {
	Mode string `json:"mode"`
}

type Schema

type Schema struct {
	Definitions map[string]Field // The definitions of the schema, basically the fields of the document
	Options     SchemaOptions    // Custom schema options, like the collection name, database name, etc.
}

func NewSchema

func NewSchema(definitions map[string]Field, opts ...SchemaOptions) Schema

Creates a new Elemental schema with the given definitions and options.

func (Schema) Field

func (s Schema) Field(path string) *Field

Retrives the Elemental field definition for the given path in the schema.

type SchemaOptions

type SchemaOptions struct {
	Collection              string                          // Custom collection name, if not set, the lowercase pluralized name of the model will be used.
	CollectionOptions       options.CreateCollectionOptions // Plain mongo driver collection options if you want to set them
	Database                string                          // Custom database name, if not set, the default database will be used
	Connection              string                          // Custom connection alias, if not set, the default connection will be used
	Auditing                bool                            // Whether to enable auditing for this model
	BypassSchemaEnforcement bool                            // Whether to bypass schema enforcement when creating a new document
}

type ServerInfo

type ServerInfo struct {
	Version    string `bson:"version" json:"version"`
	GitVersion string `bson:"gitVersion" json:"gitVersion"`
	Host       string `bson:"host" json:"host"`
	Port       int64  `bson:"port" json:"port"`
}

type Shard

type Shard struct {
	Host   string   `bson:"host" json:"host"`
	State  string   `bson:"state" json:"state"`
	Tags   []string `bson:"tags" json:"tags"`
	Uptime int64    `bson:"uptime" json:"uptime"`
}

type ShardIdentity

type ShardIdentity struct {
	ShardKeyPattern map[string]int64 `bson:"shardKeyPattern" json:"shardKeyPattern"`
	ShardName       string           `bson:"shardName" json:"shardName"`
	UUID            string           `bson:"uuid" json:"uuid"`
}

type TriggerOptions

type TriggerOptions struct {
	Filter  *primitive.M     // Optional filter to apply to the change stream
	Context *context.Context // Optional context to use for the change stream. If not provided, the default context will be used.
}

type UserFlagsData

type UserFlagsData struct {
	Cache struct {
		Reads  int64 `bson:"reads" json:"reads"`
		Writes int64 `bson:"writes" json:"writes"`
	} `bson:"cache" json:"cache"`
}

type WriteConcern

type WriteConcern struct {
	W        int64 `json:"w"`
	WTimeout int64 `json:"wtimeout"`
}

Jump to

Keyboard shortcuts

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