mgod

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2023 License: MIT Imports: 14 Imported by: 0

README

logo

mgod

mgod is a MongoDB ODM specifically designed for Go. It provides a structured way to map Go models to MongoDB collections, simplifying database interactions in Go applications.

Features

  • Reuse existing Go structs to define models and perform Mongo operations.
  • Automatic field transformation between Go and MongoDB using struct tags.
  • Easily manage meta fields in models without cluttering Go structs.
  • Supports union types, expanding data capabilities.
  • Implement strict field requirements with struct tags for data integrity.
  • Wrapper around the official Mongo Go Driver.

Requirements

  • Go 1.18 or higher.
  • MongoDB 3.6 and higher.

Installation

go get github.com/Lyearn/mgod

Basic Usage

Use existing MongoDB connection, or setup a new one to register a default database connection.

For existing database connection,

import "github.com/Lyearn/mgod"

func init() {
	// dbConn is the database connection obtained using Go Mongo Driver's Connect method.
	mgod.SetDefaultConnection(dbConn)
}

To setup a new connection,

import (
	"time"

	"github.com/Lyearn/mgod"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func init() {
	// `cfg` is optional. Can rely on default configurations by providing `nil` value in argument.
	cfg := &mgod.ConnectionConfig{Timeout: 5 * time.Second}
	dbName := "mgod-test"
	opts := options.Client().ApplyURI("mongodb://root:mgod123@localhost:27017")

	err := mgod.ConfigureDefaultConnection(cfg, dbName, opts)
}

Add tags (wherever applicable) in existing struct (or define a new model).

type User struct {
	Name     string
	EmailID  string `bson:"emailId"`
	Age      *int32 `bson:",omitempty"`
	JoinedOn string `bson:"joinedOn" mgoType:"date"`
}

Use mgod to get the entity ODM.

import (
	"github.com/Lyearn/mgod"
	"github.com/Lyearn/mgod/schema/schemaopt"
)

model := User{}
schemaOpts := schemaopt.SchemaOptions{
	Collection: "users",
	Timestamps: true,
}

userModel, _ := mgod.NewEntityMongoModel(model, schemaOpts)

Use the entity ODM to perform CRUD operations with ease.

Insert a new document.

joinedOn, _ := dateformatter.New(time.Now()).GetISOString()
userDoc := User{
	Name: "Gopher",
	EmailID: "gopher@mgod.com",
	JoinedOn: joinedOn,
}
user, _ := userModel.InsertOne(context.TODO(), userDoc)

Output:

{
	"_id": ObjectId("65697705d4cbed00e8aba717"),
	"name": "Gopher",
	"emailId": "gopher@mgod.com",
	"joinedOn": ISODate("2023-12-01T11:32:19.290Z"),
	"createdAt": ISODate("2023-12-01T11:32:19.290Z"),
	"updatedAt": ISODate("2023-12-01T11:32:19.290Z"),
	"__v": 0
}

Find documents using model properties.

users, _ := userModel.Find(context.TODO(), bson.M{"name": userDoc.Name})

Output:

[]User{
	User{
		Name: "Gopher",
		EmailID: "gopher@mgod.com",
		JoinedOn: "2023-12-01T11:32:19.290Z",
	}
}

Motivation

Creating mgod was driven by the need to simplify MongoDB interactions while keeping one schema for all in Go. Traditionally, working with MongoDB in Go involved either using separate structs for database and service logic or manually converting service structs to MongoDB documents, a process that was both time-consuming and error-prone. This lack of integration often led to redundant coding, especially when dealing with union types or adding meta fields for each MongoDB operation.

Inspired by the easy interface of MongoDB handling using Mongoose and Typegoose libraries available in Node, mgod aims to streamline these processes. It offers a more integrated approach, reducing the need to duplicate code and enhancing type safety, making MongoDB operations more intuitive and efficient in Go.

Future Scope

The current version of mgod is a stable release. However, there are plans to add a lot more features like -

  • Enable functionality to opt out of the default conversion of date fields to ISOString format.
  • Implement a setup step for storing a default Mongo connection, eliminating the need to pass it during EntityMongoModel creation.
  • Provide support for transactions following the integration of default Mongo connection logic.
  • Develop easy to use wrapper functions around MongoDB Aggregation operation.
  • Introduce automatic MongoDB collection selection based on Go struct names as a default behavior.
  • Add test cases to improve code coverage.

If you have any interesting feature requests, feel free to open an issue on GitHub issue tracker. We will be more than happy to discuss that!

Documentation

For user facing documentation, check out docs.

Contribute

For contribution guidelines, check out CONTRIBUTING.

License

mgod is licensed under the MIT License.

Documentation

Overview

Package mgod implements ODM logic for MongoDB in Go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigureDefaultConnection added in v0.3.0

func ConfigureDefaultConnection(cfg *ConnectionConfig, dbName string, opts ...*options.ClientOptions) error

ConfigureDefaultConnection opens a new connection using the provided config options and sets it as a default connection to be used by the package.

func GetSchemaCacheKey

func GetSchemaCacheKey(collName, modelNameOrVal string) string

GetSchemaCacheKey returns the cache key for the schema of a model. The cache key is in the format of <collection_name>_<model_name_or_value>. Unless we are storing the schema of a union type based on the discriminator value, the second parameter will be the model name only.

func SetDefaultConnection added in v0.3.0

func SetDefaultConnection(conn *mongo.Database)

SetDefaultConnection sets the default connection to be used by the package.

Types

type ConnectionConfig added in v0.3.0

type ConnectionConfig struct {
	// Timeout is the timeout for various operations performed on the MongoDB server like Connect, Ping, Session etc.
	Timeout time.Duration
}

ConnectionConfig is the configuration options available for a MongoDB connection.

type EntityMongoModel

type EntityMongoModel[T any] interface {
	// GetDocToInsert returns the bson.D doc to be inserted in the collection for the provided struct object.
	// This function is mainly used while creating a doc to be inserted for Union Type models because the underlying type of a union
	// type model is interface{}, so it's not possible to identify the underlying concrete type to validate and insert the doc.
	GetDocToInsert(ctx context.Context, model T) (bson.D, error)

	// InsertOne inserts a single document in the collection.
	// Model is kept as interface{} to support Union Type models i.e. accept both bson.D (generated using GetDocToInsert()) and struct object.
	InsertOne(ctx context.Context, model interface{}, opts ...*options.InsertOneOptions) (T, error)

	// InsertMany inserts multiple documents in the collection.
	// Docs is kept as interface{} to support Union Type models i.e. accept both []bson.D (generated using GetDocToInsert()) and []struct objects.
	InsertMany(ctx context.Context, docs interface{}, opts ...*options.InsertManyOptions) ([]T, error)

	// UpdateMany updates multiple filtered documents in the collection based on the provided update query.
	UpdateMany(ctx context.Context, filter, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

	// BulkWrite performs multiple write operations on the collection at once.
	// Currently, only InsertOne, UpdateOne, and UpdateMany operations are supported.
	BulkWrite(ctx context.Context, bulkWrites []mongo.WriteModel, opts ...*options.BulkWriteOptions) (*mongo.BulkWriteResult, error)

	// Find returns all documents in the collection matching the provided filter.
	Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) ([]T, error)

	// FindOne returns a single document from the collection matching the provided filter.
	FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) (*T, error)

	// FindOneAndUpdate returns a single document from the collection based on the provided filter and updates it.
	FindOneAndUpdate(ctx context.Context, filter, update interface{}, opts ...*options.FindOneAndUpdateOptions) (T, error)

	// DeleteOne deletes a single document in the collection based on the provided filter.
	DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

	// DeleteMany deletes multiple documents in the collection based on the provided filter.
	DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

	// CountDocuments returns the number of documents in the collection for the provided filter.
	CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (int64, error)

	// Distinct returns the distinct values for the provided field name in the collection for the provided filter.
	Distinct(ctx context.Context, fieldName string, filter interface{}, opts ...*options.DistinctOptions) ([]interface{}, error)

	// Aggregate performs an aggregation operation on the collection and returns the results.
	Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) ([]bson.D, error)
}

EntityMongoModel is a generic interface of available wrapper functions on MongoDB collection.

func NewEntityMongoModel

func NewEntityMongoModel[T any](modelType T, schemaOpts schemaopt.SchemaOptions) (EntityMongoModel[T], error)

NewEntityMongoModel returns a new instance of EntityMongoModel for the provided model type and options.

Directories

Path Synopsis
Package bsondoc builds on an existing bson doc according to the provided entity model schema.
Package bsondoc builds on an existing bson doc according to the provided entity model schema.
Package dateformatter provides utilities to get date time in different formats.
Package dateformatter provides utilities to get date time in different formats.
Package schema provides utilities to build the schema tree for the entity model.
Package schema provides utilities to build the schema tree for the entity model.
fieldopt
Package fieldopt provides custom options for schema fields.
Package fieldopt provides custom options for schema fields.
metafield
Package metafield defines and provide functions on custom meta fields for the schema.
Package metafield defines and provide functions on custom meta fields for the schema.
transformer
Package transformer provides custom transformers for schema fields.
Package transformer provides custom transformers for schema fields.

Jump to

Keyboard shortcuts

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