Skip to content

senrok/go-odm

Repository files navigation

A project of SENROK Open Source

Go ODM

Go-odm, a Golang Object Document Mapping for MongoDB.

GoDoc

Table of contents

Features

  • Define your models and perform CRUD operations with hooks before/after each operation.
  • Built-in Soft-Delete
  • Support the Multi-Database Instance
  • Wrap the official Mongo Go Driver.

Installation

go get github.com/senrok/go-odm

Get started

Setup a db config:

	opts, err := DefaultOpts(SetDatabase(MONGODB_URL, MONGODB_DB_NAME))

Define Model

type Doc struct {
	DefaultModel `bson:",inline"`

	Name string `bson:"name"`
	Age  int    `bson:"age"`
}

Insert a new Document

	err := opts.Coll(&doc).Create(context.TODO(), &doc)

Update a document

        docs:=getYourData()
        updatedAt := docs[0].UpdatedAt
        docs[0].Name = "weny updated"
        err := opts.Coll(&Doc{}).UpdateOne(context.TODO(), docs[0])

Soft-Delete a document

	err := opts.Coll(&Doc{}).SoftDeleteOne(context.TODO(), data[0])

Restore a document

	err = opts.Coll(&Doc{}).RestoreOne(context.TODO(), data[0])

Delete a document

	err := opts.Coll(&Doc{}).DeleteOne(context.TODO(), data[0])

Find a document

	err := opts.Coll(&Doc{}).FindOne(context.TODO(), bson.M{"name": "weny"}, &result)

Transactions

    err := opts.TransactionWithCtx(context.TODO(), func(session mongo.Session, sc mongo.SessionContext) error {

		err := opts.Coll(d).Create(sc, d)

		if err != nil {
			return err
		}

		return session.CommitTransaction(sc)
	})

Documentation

GoDoc

License

The Project is licensed under the Apache License.