Documentation
¶
Index ¶
- Constants
- Variables
- func ClientTransaction(alias string, fn func(ctx mongo.SessionContext) (any, error)) (any, error)
- func Connect(arg any) mongo.Client
- func Disconnect(aliases ...string) error
- func DropAllDatabases(alias ...string)
- func GetConnection(alias ...string) *mongo.Client
- func OnConnectionEvent(event string, handler func(), alias ...string)
- func Ping(alias ...string) error
- func RemoveConnectionEvent(event string, alias ...string)
- func Transaction(fn func(ctx mongo.SessionContext) (any, error)) (any, error)
- func TransactionBatch(queries ...ModelInterface[any]) ([]any, []any)
- func UseDatabase(database string, alias ...string) *mongo.Database
- func UseDefaultDatabase(alias ...string) *mongo.Database
- type Audit
- type AuditType
- type CollectionStats
- type ConnectionOptions
- type Field
- type FieldType
- type Model
- func (m Model[T]) AddToSet(field string, values ...any) Model[T]
- func (m Model[T]) AvgObjSize(ctx ...context.Context) int64
- func (m Model[T]) Between(minimum, maximum any) Model[T]
- func (m Model[T]) Client() *mongo.Client
- func (m Model[T]) Clone() Model[T]
- func (m Model[T]) Collection() *mongo.Collection
- func (m Model[T]) Connection() *mongo.Client
- func (m Model[T]) CountDocuments(query ...primitive.M) Model[T]
- func (m Model[T]) Create(doc T) Model[T]
- func (m Model[T]) CreateCollection(ctx ...context.Context) *mongo.Collection
- func (m Model[T]) CreateMany(docs []T) Model[T]
- func (m Model[T]) CurrentDate(field string) Model[T]
- func (m Model[T]) Database() *mongo.Database
- func (m Model[T]) Dec(field string, value int) Model[T]
- func (m Model[T]) Delete(doc T) Model[T]
- func (m Model[T]) DeleteByID(id any) Model[T]
- func (m Model[T]) DeleteMany(query ...primitive.M) Model[T]
- func (m Model[T]) DeleteOne(query ...primitive.M) Model[T]
- func (m *Model[T]) DisableSoftDelete()
- func (m Model[T]) Distinct(field string, query ...primitive.M) Model[T]
- func (m Model[T]) Div(field string, value int) Model[T]
- func (m Model[T]) Drop(ctx ...context.Context)
- func (m Model[T]) DropIndex(indexName string, ctx ...context.Context) (bson.Raw, error)
- func (m Model[T]) DropIndexes(ctx ...context.Context) (bson.Raw, error)
- func (m Model[T]) ElementMatches(query primitive.M) Model[T]
- func (m Model[T]) EnableAuditing(ctx ...context.Context)
- func (m *Model[T]) EnableSoftDelete(deletedAtFieldName ...string)
- func (m Model[T]) Equals(value any) Model[T]
- func (m Model[T]) EstimatedDocumentCount(ctx ...context.Context) int64
- func (m Model[T]) Exec(ctx ...context.Context) any
- func (m Model[T]) ExecInt(ctx ...context.Context) int
- func (m Model[T]) ExecInto(result any, ctx ...context.Context)
- func (m Model[T]) ExecPtr(ctx ...context.Context) *T
- func (m Model[T]) ExecSS(ctx ...context.Context) []string
- func (m Model[T]) ExecT(ctx ...context.Context) T
- func (m Model[T]) ExecTP(ctx ...context.Context) PaginateResult[T]
- func (m Model[T]) ExecTT(ctx ...context.Context) []T
- func (m Model[T]) Exists(value bool) Model[T]
- func (m Model[T]) Find(query ...primitive.M) Model[T]
- func (m Model[T]) FindByID(id any) Model[T]
- func (m Model[T]) FindByIDAndDelete(id any) Model[T]
- func (m Model[T]) FindByIDAndReplace(id any, doc any, opts ...*options.FindOneAndReplaceOptions) Model[T]
- func (m Model[T]) FindByIDAndUpdate(id any, doc any, opts ...*options.FindOneAndUpdateOptions) Model[T]
- func (m Model[T]) FindOne(query ...primitive.M) Model[T]
- func (m Model[T]) FindOneAndDelete(query ...primitive.M) Model[T]
- func (m Model[T]) FindOneAndReplace(query *primitive.M, doc any, opts ...*options.FindOneAndReplaceOptions) Model[T]
- func (m Model[T]) FindOneAndUpdate(query *primitive.M, doc any, opts ...*options.FindOneAndUpdateOptions) Model[T]
- func (m Model[T]) GreaterThan(value any) Model[T]
- func (m Model[T]) GreaterThanOrEquals(value any) Model[T]
- func (m Model[T]) Has(value string) Model[T]
- func (m Model[T]) In(values ...any) Model[T]
- func (m Model[T]) Inc(field string, value int) Model[T]
- func (m Model[T]) InsertMany(docs []T) Model[T]
- func (m Model[T]) InvalidateTriggers()
- func (m Model[T]) IsArray() Model[T]
- func (m Model[T]) IsBinary() Model[T]
- func (m Model[T]) IsBoolean() Model[T]
- func (m Model[T]) IsCapped(ctx ...context.Context) bool
- func (m Model[T]) IsCodeWithScope() Model[T]
- func (m Model[T]) IsDBPointer() Model[T]
- func (m Model[T]) IsDateTime() Model[T]
- func (m Model[T]) IsDecimal128() Model[T]
- func (m Model[T]) IsDouble() Model[T]
- func (m Model[T]) IsInt32() Model[T]
- func (m Model[T]) IsInt64() Model[T]
- func (m Model[T]) IsJavaScript() Model[T]
- func (m Model[T]) IsNull() Model[T]
- func (m Model[T]) IsObjectID() Model[T]
- func (m Model[T]) IsRegex() Model[T]
- func (m Model[T]) IsString() Model[T]
- func (m Model[T]) IsSymbol() Model[T]
- func (m Model[T]) IsTimestamp() Model[T]
- func (m Model[T]) IsType(value bsontype.Type) Model[T]
- func (m Model[T]) IsUndefined() Model[T]
- func (m Model[T]) LessThan(value any) Model[T]
- func (m Model[T]) LessThanOrEquals(value any) Model[T]
- func (m Model[T]) Limit(limit int64) Model[T]
- func (m Model[T]) Max(field string, value int) Model[T]
- func (m Model[T]) Min(field string, value int) Model[T]
- func (m Model[T]) Mod(divisor, remainder int) Model[T]
- func (m Model[T]) Mul(field string, value int) Model[T]
- func (m Model[T]) New() Model[T]
- func (m Model[T]) NotEquals(value any) Model[T]
- func (m Model[T]) NotIn(values ...any) Model[T]
- func (m Model[T]) NumberOfIndexes(ctx ...context.Context) int64
- func (m Model[T]) OnCollectionDrop(f func(), opts ...TriggerOptions) *mongo.ChangeStream
- func (m Model[T]) OnCollectionRename(f func(), opts ...TriggerOptions) *mongo.ChangeStream
- func (m Model[T]) OnDelete(f func(id primitive.ObjectID), opts ...TriggerOptions) *mongo.ChangeStream
- func (m Model[T]) OnInsert(f func(doc T), opts ...TriggerOptions) *mongo.ChangeStream
- func (m Model[T]) OnReplace(f func(doc T), opts ...TriggerOptions) *mongo.ChangeStream
- func (m Model[T]) OnStreamInvalidate(f func(), opts ...TriggerOptions) *mongo.ChangeStream
- func (m Model[T]) OnUpdate(f func(doc T), opts ...TriggerOptions) *mongo.ChangeStream
- func (m Model[T]) Or() Model[T]
- func (m Model[T]) OrFail(err ...error) Model[T]
- func (m Model[T]) OrWhere(field string, equals ...any) Model[T]
- func (m Model[T]) Paginate(page, limit int64) Model[T]
- func (m Model[T]) Ping(ctx ...context.Context) error
- func (m Model[T]) Pop(field string, value ...int) Model[T]
- func (m Model[T]) Populate(values ...any) Model[T]
- func (m Model[T]) PostDeleteMany(f func(result *mongo.DeleteResult, err error) bool)
- func (m Model[T]) PostDeleteOne(f func(result *mongo.DeleteResult, err error) bool)
- func (m Model[T]) PostFind(f func(doc *[]T) bool)
- func (m Model[T]) PostFindOneAndDelete(f func(doc *T) bool)
- func (m Model[T]) PostFindOneAndReplace(f func(doc *T) bool)
- func (m Model[T]) PostFindOneAndUpdate(f func(doc *T) bool)
- func (m Model[T]) PostSave(f func(doc *bson.M) bool)
- func (m Model[T]) PostUpdateOne(f func(result *mongo.UpdateResult, err error) bool)
- func (m Model[T]) PreDeleteMany(f func(filters *primitive.M) bool)
- func (m Model[T]) PreDeleteOne(f func(filters *primitive.M) bool)
- func (m Model[T]) PreFindOneAndDelete(f func(filters *primitive.M) bool)
- func (m Model[T]) PreFindOneAndReplace(f func(filters *primitive.M, doc any) bool)
- func (m Model[T]) PreFindOneAndUpdate(f func(filters *primitive.M, doc any) bool)
- func (m Model[T]) PreSave(f func(doc *bson.M) bool)
- func (m Model[T]) PreUpdateOne(f func(doc any) bool)
- func (m Model[T]) Pull(field string, value any) Model[T]
- func (m Model[T]) PullAll(field string, values ...any) Model[T]
- func (m Model[T]) Push(field string, values ...any) Model[T]
- func (m Model[T]) QS(query string) Model[T]
- func (m Model[T]) QSR(result fq.Result) Model[T]
- func (m Model[T]) Regex(pattern string, options ...string) Model[T]
- func (m Model[T]) Rename(field string, newField string) Model[T]
- func (m Model[T]) ReplaceByID(id any, doc any, opts ...*options.ReplaceOptions) Model[T]
- func (m Model[T]) ReplaceOne(query *primitive.M, doc any, opts ...*options.ReplaceOptions) Model[T]
- func (m Model[T]) Save(doc T) Model[T]
- func (m Model[T]) Schedule(spec string, onExecutionError ...func(any)) Model[T]
- func (m Model[T]) Select(fields ...any) Model[T]
- func (m Model[T]) Set(doc any) Model[T]
- func (m Model[T]) SetCollection(collection string) Model[T]
- func (m Model[T]) SetConnection(connection string) Model[T]
- func (m Model[T]) SetDatabase(database string) Model[T]
- func (m Model[T]) Shift(field string) Model[T]
- func (m Model[T]) Size(value int) Model[T]
- func (m Model[T]) Skip(skip int64) Model[T]
- func (m Model[T]) Sort(args ...any) Model[T]
- func (m Model[T]) Stats(ctx ...context.Context) CollectionStats
- func (m Model[T]) StorageSize(ctx ...context.Context) int64
- func (m Model[T]) SyncIndexes(ctx ...context.Context)
- func (m Model[T]) TotalIndexSize(ctx ...context.Context) int64
- func (m Model[T]) TotalSize(ctx ...context.Context) int64
- func (m Model[T]) Unschedule(id int)
- func (m Model[T]) UnscheduleAll()
- func (m Model[T]) Unset(doc any) Model[T]
- func (m Model[T]) UpdateByID(id any, doc any, opts ...*options.UpdateOptions) Model[T]
- func (m Model[T]) UpdateMany(query *primitive.M, doc any, opts ...*options.UpdateOptions) Model[T]
- func (m Model[T]) UpdateOne(query *primitive.M, doc any, opts ...*options.UpdateOptions) Model[T]
- func (m Model[T]) Upsert() Model[T]
- func (m Model[T]) Validate(doc T)
- func (m Model[T]) Where(field string, equals ...any) Model[T]
- type ModelInterface
- type PaginateResult
- type ReadPreference
- type Schema
- type SchemaOptions
- type ServerInfo
- type Shard
- type ShardIdentity
- type TriggerOptions
- type UserFlagsData
- type WriteConcern
Constants ¶
const AuditUserFallback = "System"
const ConnectionTimeout = 30 * time.Second
The default connection timeout for elemental connections
const CtxUser = "user"
const EventDeploymentDiscovered = "DeploymentDiscovered"
Variables ¶
var ( ErrURIRequired = errors.New("URI is required") ErrInvalidConnectionArgument = errors.New("invalid connection argument") ErrMustPairSortArguments = errors.New("sort arguments must be in pairs") )
var Array = reflect.Array
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, }))
var Bool = reflect.Bool
var BoolMap = reflect.TypeOf(map[string]bool{})
var BoolSlice = reflect.TypeOf([]bool{})
var Float32 = reflect.Float32
var Float32Map = reflect.TypeOf(map[string]float32{})
var Float32Slice = reflect.TypeOf([]float32{})
var Float64 = reflect.Float64
var Float64Map = reflect.TypeOf(map[string]float64{})
var Float64Slice = reflect.TypeOf([]float64{})
var GetClient = GetConnection
Same as 'GetConnection' method
var Int = reflect.Int
var Int32 = reflect.Int32
var Int32Map = reflect.TypeOf(map[string]int32{})
var Int32Slice = reflect.TypeOf([]int32{})
var Int64 = reflect.Int64
var Int64Map = reflect.TypeOf(map[string]int64{})
var Int64Slice = reflect.TypeOf([]int64{})
var IntMap = reflect.TypeOf(map[string]int{})
var IntSlice = reflect.TypeOf([]int{})
var Interface = reflect.Interface
var Map = reflect.Map
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.
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.
var ObjectID = reflect.TypeOf(primitive.NilObjectID)
var ObjectIDSlice = reflect.TypeOf([]primitive.ObjectID{})
var Slice = reflect.Slice
var String = reflect.String
var StringMap = reflect.TypeOf(map[string]string{})
var StringSlice = reflect.TypeOf([]string{})
var Struct = reflect.Struct
var Time = reflect.TypeOf(time.Time{})
var Uint = reflect.Uint
var Uint32 = reflect.Uint32
var Uint32Map = reflect.TypeOf(map[string]uint32{})
var Uint32Slice = reflect.TypeOf([]uint32{})
var Uint64 = reflect.Uint64
var Uint64Map = reflect.TypeOf(map[string]uint64{})
var Uint64Slice = reflect.TypeOf([]uint64{})
var UintMap = reflect.TypeOf(map[string]uint{})
var UintSlice = reflect.TypeOf([]uint{})
Functions ¶
func ClientTransaction ¶
Essentially the same as Transaction, but with an alias which points to the connection to use
func Connect ¶ added in v1.7.0
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
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
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
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
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
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 ¶
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
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
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 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 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 ¶
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 ¶
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 ¶
The average size of each document in the collection
func (Model[T]) Between ¶
Extends the query to return only documents that are between the given values.
func (Model[T]) Client ¶ added in v1.8.1
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
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
Returns the underlying client instance this model uses
func (Model[T]) CountDocuments ¶
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 ¶
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 ¶
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 ¶
Extends the query to set the value of the given field to the current date
func (Model[T]) Delete ¶
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 ¶
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 ¶
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 ¶
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 ¶
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]) DropIndexes ¶
Drops all indexes for this model except the default `_id` index.
func (Model[T]) ElementMatches ¶
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 ¶
Enables auditing for the current model.
func (*Model[T]) EnableSoftDelete ¶ added in v0.0.7
Enables soft delete for the model.
func (Model[T]) EstimatedDocumentCount ¶
Returns the count of all documents in a collection or view
func (Model[T]) Exec ¶
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
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
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
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
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
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
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]) Find ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
Extends the query to return only documents that are greater than the given value.
func (Model[T]) GreaterThanOrEquals ¶
Extends the query to return only documents that are greater than or equal to the given value.
func (Model[T]) Has ¶
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 ¶
Extends the query to return only documents where the given field has a value equal to any of the given values.
func (Model[T]) InsertMany ¶
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]) IsCapped ¶
Returns true if the model collection is a capped collection, otherwise returns false
func (Model[T]) IsCodeWithScope ¶
func (Model[T]) IsDBPointer ¶
func (Model[T]) IsDateTime ¶
func (Model[T]) IsDecimal128 ¶
func (Model[T]) IsJavaScript ¶
func (Model[T]) IsObjectID ¶
func (Model[T]) IsTimestamp ¶
func (Model[T]) IsUndefined ¶
func (Model[T]) LessThan ¶
Extends the query to return only documents that are less than the given value.
func (Model[T]) LessThanOrEquals ¶
Extends the query to return only documents that are less than or equal to the given value.
func (Model[T]) Max ¶
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 ¶
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 ¶
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]) New ¶
Signals the query to return the new document instead of the original document after an update
func (Model[T]) NotEquals ¶
Extends the query to return only documents that do not equal the given value.
func (Model[T]) NotIn ¶
Extends the query to return only documents where the given field does not have any of the given values.
func (Model[T]) NumberOfIndexes ¶
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]) OrFail ¶
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 ¶
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 ¶
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]) Pop ¶
Extends the query to remove the last element from the array of the given field
func (Model[T]) Populate ¶
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]) PostFindOneAndDelete ¶
func (Model[T]) PostFindOneAndReplace ¶
func (Model[T]) PostFindOneAndUpdate ¶
func (Model[T]) PostUpdateOne ¶
func (m Model[T]) PostUpdateOne(f func(result *mongo.UpdateResult, err error) bool)
func (Model[T]) PreFindOneAndDelete ¶
func (Model[T]) PreFindOneAndReplace ¶ added in v1.19.0
func (Model[T]) PreFindOneAndUpdate ¶
func (Model[T]) PreUpdateOne ¶
func (Model[T]) Pull ¶
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 ¶
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]) QS ¶
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
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 ¶
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]) ReplaceByID ¶
Extends the query with a replace operation matching the given id The id can be a string or an ObjectID.
func (Model[T]) ReplaceOne ¶
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 ¶
Extends the query with an upsert operation matching the id of the given document
func (Model[T]) Schedule ¶
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 ¶
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]) SetCollection ¶
Sets a temporary collection for this model. This collection will be used for the next operation only.
func (Model[T]) SetConnection ¶
Sets a temporary connection for this model. This connection will be used for the next operation only.
func (Model[T]) SetDatabase ¶
Sets a temporary database for this model. This database will be used for the next operation only.
func (Model[T]) Shift ¶
Extends the query to remove the first element from the array of the given field
func (Model[T]) Size ¶
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]) Sort ¶
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 ¶
The total amount of storage in bytes allocated to this collection for document storage
func (Model[T]) SyncIndexes ¶
Creates or updates the indexes for this model. This method will only create the indexes if they do not exist.
func (Model[T]) TotalIndexSize ¶
The total size of all indexes for the collection
func (Model[T]) TotalSize ¶
The total size in bytes of the data in the collection plus the size of every index on the collection
func (Model[T]) Unschedule ¶
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]) UpdateByID ¶
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 ¶
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 ¶
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]) 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.
type ModelInterface ¶ added in v1.2.0
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.
}
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 ShardIdentity ¶
type TriggerOptions ¶
type UserFlagsData ¶
type WriteConcern ¶
Source Files
¶
- connection.go
- connection_events.go
- errors.go
- model.go
- model_actions.go
- model_audit.go
- model_is.go
- model_meta.go
- model_meta_types.go
- model_middleware.go
- model_ops.go
- model_paginate.go
- model_plugins.go
- model_populate.go
- model_query.go
- model_query_delete.go
- model_query_update.go
- model_schedule.go
- model_triggers.go
- model_types.go
- model_utils.go
- schema.go
- schema_reflect_types.go
- schema_types.go
- schema_validator.go
- transaction.go