morm

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2024 License: MIT Imports: 11 Imported by: 0

README

Morm

Morm is a powerful Object Document Mapper (ODM) for Golang, inspired by Mongoose, designed to be developer-friendly and feature-rich.

Go Report Card MIT license Go.Dev reference

Overview

  • Almost Full-Featured Object Document Mapper
  • Associations (Embedded Documents, References)
  • Hooks (Before/After Create/Update/Delete/Find)
  • Table joining with Populate
  • Transactions, Nested Transactions
  • Context Support, Prepared Statement Mode, DryRun Mode
  • Batch Insert, FindInBatches, Find To Map
  • Mongoose like Query Builder, Sort, Limit, Skip, etc
  • Logger
  • Extendable, flexible plugin API: Database Resolver (Multiple Databases, Read/Write Splitting), Prometheus…
  • Every feature comes with tests
  • Developer Friendly

Getting Started

To get started with Morm, follow these steps:

1. Install Morm

Install the package using go get:

go get -u github.com/devsamahd/morm

For more on this package

Contributing

You can help make Morm better, check out things you can do

Contributors

Thank you for contributing to Morm!

License

© Devsamahd, 2024

Released under the MIT License

Documentation

Overview

Package morm provides a simple MongoDB wrapper for Go applications.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ToUpdateStruct

func ToUpdateStruct(data interface{}) (primitive.M, error)

ToUpdateStruct converts a struct to a primitive.M for MongoDB update operations. It marshals the input struct to BSON and then unmarshals it to a primitive.M.

Parameters:

  • data: The struct to be converted.

Returns:

  • primitive.M: The converted BSON data.
  • error: An error if the conversion fails.

Example:

type UpdateData struct {
  Field1 string `bson:"field1"`
  Field2 int    `bson:"field2"`
}

data := UpdateData{"value1", 42}
converted, err := ToUpdateStruct(data)
if err != nil {
  // Handle error
}

This function is useful for converting a struct to the format required for MongoDB update operations.

Types

type Collect

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

Collect represents a MongoDB collection and model information.

func (*Collect) Aggregate

func (c *Collect) Aggregate(pipeline interface{}, ctx ...context.Context) (*mongo.Cursor, error)

Aggregate performs an aggregation query on the MongoDB collection using the specified pipeline. It takes a pipeline as an interface{}, representing the aggregation stages.

Parameters:

  • pipeline: The interface{} representing the aggregation pipeline stages.
  • ctx: Optional context.Context for the aggregation operation. If not provided, the default context will be used.

Returns:

  • *mongo.Cursor: A cursor pointing to the result of the aggregation query.
  • error: An error if any occurred during the aggregation operation.

type CollectQueryBuilder

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

CollectQueryBuilder represents a query builder for MongoDB operations on a collection.

func Collection

func Collection(collectionName string, model interface{}) (*CollectQueryBuilder, error)

Collection creates a new Collect instance for the specified collection and model. It takes the collection name and a model (pointer to a struct) as parameters. Returns a CollectQueryBuilder for building queries on the collection.

func (*CollectQueryBuilder) Create

func (qb *CollectQueryBuilder) Create(model interface{}, ctx ...context.Context) (primitive.ObjectID, error)

Create inserts a new document into the specified collection.

Parameters:

  • model: The model representing the document to be inserted.
  • ctx: Optional context.Context for the create operation. If not provided, the default context will be used.

Returns:

  • primitive.ObjectID: The ObjectID of the newly inserted document.
  • error: An error if any occurred during the insert operation.

func (*CollectQueryBuilder) Delete

func (qb *CollectQueryBuilder) Delete(filter interface{}, ctx ...context.Context) error

Delete deletes a single document from the specified collection based on the provided filter.

Parameters:

  • filter: The filter to match documents for deletion.
  • ctx: Optional context.Context for the delete operation. If not provided, the default context will be used.

Returns:

  • error: An error if any occurred during the delete operation.

func (*CollectQueryBuilder) DeleteMany

func (qb *CollectQueryBuilder) DeleteMany(filter interface{}, ctx ...context.Context) (int64, error)

DeleteMany deletes multiple documents from the specified collection based on the provided filter.

Parameters:

  • filter: The filter to match documents for deletion.
  • ctx: Optional context.Context for the delete operation. If not provided, the default context will be used.

Returns:

  • int64: The number of documents deleted.
  • error: An error if any occurred during the delete operation.

func (*CollectQueryBuilder) Exec

func (qb *CollectQueryBuilder) Exec() (interface{}, error)

Exec executes the MongoDB query and returns the result. It performs the specified MongoDB operation (e.g., find, findOne) based on the query configuration.

Returns:

  • result: A pointer to the result model where the query result will be decoded.
  • error: An error if the query execution fails.

Example:

var user User
err := qb.Filter(bson.D{{"name", "John"}}).Exec(&user)
if err != nil {
  // Handle error
}

This method is used to execute the configured MongoDB query and retrieve the result. The type of 'result' should be a pointer to the model struct representing the collection documents. The actual operation performed depends on the query method set using the Method() method.

func (*CollectQueryBuilder) Find

func (qb *CollectQueryBuilder) Find(filter ...interface{}) *CollectQueryBuilder

Find sets the filter for the MongoDB query in the CollectQueryBuilder and specifies it's a find operation. Additional filter conditions can be provided as optional arguments.

func (*CollectQueryBuilder) FindOne

func (qb *CollectQueryBuilder) FindOne(filter interface{}) *CollectQueryBuilder

FindOne sets the filter for the MongoDB query in the CollectQueryBuilder and specifies it's a findone operation. The result is decoded into the provided result interface.

func (*CollectQueryBuilder) FindOneAndRemove

func (qb *CollectQueryBuilder) FindOneAndRemove(filter interface{}, ctx ...context.Context) (interface{}, error)

FindOneAndRemove finds a single document in the specified collection based on the filter and removes it. It returns the removed document.

func (*CollectQueryBuilder) FindOneAndUpdate

func (qb *CollectQueryBuilder) FindOneAndUpdate(filter interface{}, update interface{}, ctx ...context.Context) (interface{}, error)

FindOneAndUpdate finds a single document in the specified collection based on the filter and updates it. It returns the updated document. The update includes setting the "updatedAt" field to the current time.

func (*CollectQueryBuilder) Limit

Limit sets the maximum number of documents to return in the MongoDB query. It specifies the maximum number of documents to return in the result set.

Parameters:

  • n: The maximum number of documents to return.

Example:

qb.Limit(20).Sort(bson.D{{"timestamp", -1}}).Execute()

This method is commonly used to control the size of the result set and manage query performance.

func (*CollectQueryBuilder) Populate

func (qb *CollectQueryBuilder) Populate(fields []string) *CollectQueryBuilder

Populate sets the fields to populate in the MongoDB query result. It takes a slice of strings representing the field names to populate.

Example:

qb.Populate([]string{"Author", "Comments"})

This method is commonly used to specify fields that are references to other collections and need to be populated with their actual values in the query result.

Note: Ensure that the provided field names are valid and exist in the MongoDB documents.

func (*CollectQueryBuilder) Projection

func (qb *CollectQueryBuilder) Projection(projection bson.D) *CollectQueryBuilder

Projection sets the projection fields for the MongoDB query. It specifies the fields to include or exclude from the query result.

Parameters:

  • projection: A BSON document representing the projection.

Example:

qb.Projection(bson.D{{"name", 1}, {"age", 1}}).Skip(5).Execute()

This method is useful for selecting specific fields in the query result.

func (*CollectQueryBuilder) Skip

Skip sets the number of documents to skip in the MongoDB query. It specifies the number of documents to skip before starting to return documents.

Parameters:

  • n: The number of documents to skip.

Example:

qb.Skip(10).Limit(5).Execute()

This method is useful for implementing pagination in query results.

func (*CollectQueryBuilder) Sort

Sort sets the sort order for the MongoDB query. It specifies the order in which the query result should be sorted.

Parameters:

  • sort: A BSON document representing the sort order.

Example:

qb.Sort(bson.D{{"timestamp", -1}}).Limit(10).Execute()

This method is commonly used for ordering query results based on one or more fields.

func (*CollectQueryBuilder) Update

func (qb *CollectQueryBuilder) Update(filter interface{}, update interface{}, ctx ...context.Context) error

Update updates multiple documents in the specified collection based on the filter and update parameters.

Parameters:

  • filter: The filter criteria to identify the documents to update.
  • update: The update data to be applied to the documents.
  • ctx: Optional context for the MongoDB operation.

Returns:

  • error: An error if the update operation fails.

Example:

filter := bson.D{{"status", "pending"}}
update := bson.D{{"$set", bson.D{{"status", "processed"}}}}
err := qb.Update(filter, update)
if err != nil {
  // Handle error
}

This method is useful for updating multiple documents in a MongoDB collection.

func (*CollectQueryBuilder) UpdateOne

func (qb *CollectQueryBuilder) UpdateOne(filter interface{}, update interface{}) error

UpdateOne updates a single document in the specified collection based on the filter and update parameters.

Parameters:

  • filter: The filter criteria to identify the document to update.
  • update: The update data to be applied to the document.

Returns:

  • error: An error if the update operation fails.

Example:

filter := bson.D{{"name", "John"}}
update := bson.D{{"$set", bson.D{{"age", 30}}}}
err := qb.UpdateOne(filter, update)
if err != nil {
  // Handle error
}

This method is useful for updating a single document in a MongoDB collection.

type Model

type Model struct {
	ID        primitive.ObjectID `bson:"_id,omitempty" json:"_id"`
	CreatedAt time.Time          `bson:"createdAt"`
	UpdatedAt time.Time          `bson:"updatedAt"`
}

Model represents a base MongoDB document model with common fields like ID, CreatedAt, and UpdatedAt. It is embedded in other structs to provide standardized fields for MongoDB documents.

type MongoDB

type MongoDB struct {
	Client *mongo.Client
	DBName string
}

MongoDB represents the MongoDB client and database information.

var MongoDBInstance *MongoDB

MongoDBInstance represents a global instance of MongoDB connection.

func Connect

func Connect(uri string, dbName string) (*MongoDB, error)

Connect establishes a connection to MongoDB and returns a MongoDB instance. It takes the MongoDB URI and the name of the database as parameters.

Jump to

Keyboard shortcuts

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