goose

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2020 License: Apache-2.0 Imports: 18 Imported by: 0

README

goose

A golang struct tags(schema) style mongo package hyper interface base on mongo-driver, inspired by Node.JS package mongoose

Examples

You can check the /examples/ folder.

cd ./examples && go run ./simple.go

Document

Database

Once you connect database in main function, you can new a model in everywhere.

Connect to Mongo by .env file
func main() {
  err := godotenv.Load()
  if err != nil {
    t.Error(err)
  }
  db, err := goose.NewMongoDatabase(&goose.DatabaseOptions{
    UsingEnv: true,
  })
  if err != nil {
    t.Fatal(err)
  }
  defer db.Close()
  
  // do something else
}
Connect to Mongo
  mongoConnStringTemplate := "mongodb://%s:%s@%s:%s"
  connectionURI := fmt.Sprintf(mongoConnStringTemplate, "root", "example", "localhost", "27017")

  db, err := goose.NewMongoDatabase(&goose.DatabaseOptions{
    DatabaseName: "test",
    URL:          connectionURI,
  })
  if err != nil {
    t.Fatal(err)
  }
  defer db.Close()

  // do something else
Model
Init a model
// define struct as a schema
type User struct {
  ID    primitive.ObjectID `goose:"objectID,primary,required" bson="_id"`
  Name  string             `goose:"required" bson="name"`
  Email string             `goose:"required" bson="email"`
}

func main() {
  // init model with some data
  user := &User{
    ID:    primitive.NewObjectID(),
    Name:  "Pascal",
    Email: "pascal@example",
  }

  // new a model
  userModel := goose.NewModel("TestUsers", user)

  // update model data
  user.Name = "Pascal Lin"

  // save model, create or update
  err = userModel.Save()
  if err != nil {
    t.Fatal(err)
  }
}
Tags

Using goose, you can using tags to specific some data relationship and normal business logic, there is the tag list below:

TagName Usage Description
primary goose="primary" define a primary key for you collection model
index goose="index" add field indexes to collection
default goose:"default='test'" or goose:"default=1" or goose:"default=1.1" or goose:"default=false" set default value for model field, string should be quote by ' and not including ,; int and float will convert to 64 bit, you should not add bson:omitempty if default=0
populate goose="populate=User" or goose="populate=User" ref="Users" foreignKey="userId" populate data from other collection, ref and foreignKey is optional
createdAt goose:"createdAt" set a created time
updatedAt goose:"createdAt" set a updated time
deletedAt goose:"createdAt" set a soft delete time and as soft delete signal
- goose:"-" do nothing

A whole example:

type Post struct {
  ID          primitive.ObjectID `goose:"primary" bson:"_id,omitempty"`
  UserID      primitive.ObjectID `goose:"populate=User" bson:"userId,omitempty" ref:"TestUsers" forignKey:"_id"`
  Title       string             `goose:"-" bson:"title,omitempty"`
  CreatedTime time.Time          `goose:"index,createdAt" bson:"createdTime,omitempty"`
  UpdatedTime time.Time          `goose:"updatedAt" bson:"updatedTime,omitempty"`
}
Collection

You can still using collection from mongo-driver database as usual. such as,

singleResult := goose.DB.Collection("TestUsers").FindOne(context.Background(), bson.M{"_id": userID})
var userResult User
singleResult.Decode(&userResult)
fmt.Println("user: ", userResult)

Development

Run godoc documents

git clone https://github.com/pascallin/goose.git

go get -v  golang.org/x/tools/cmd/godoc

godoc -http=:6060

# visit http://localhost:6060/pkg/github.com/pascallin/goose/pkg/mongo/
Test
go test -v ./test

Documentation

Index

Constants

This section is empty.

Variables

DB a mongo database instance after init

Functions

This section is empty.

Types

type Database

type Database struct {
	DB      *mongo.Database
	Client  *mongo.Client
	Context context.Context
}

Database is a base struct for goose mongo

func NewMongoDatabase

func NewMongoDatabase(ops *DatabaseOptions) (*Database, error)

NewMongoDatabase new a goose mongo database

func (*Database) Close

func (d *Database) Close() error

Close close database connection

type DatabaseOptions

type DatabaseOptions struct {
	ConnectTimeout time.Duration `validate:"isdefault=5"`               // Timeout operations after N seconds
	URL            string        `validate:"required_without=UsingEnv"` // connection URL string
	UsingEnv       bool          `validate:"required_without=URL"`      // using env
	DatabaseName   string        `validate:"required_without=UsingEnv"` // databaseName
	// contains filtered or unexported fields
}

DatabaseOptions init database options

type Field

type Field struct {
	StructFieldName string
	BsonName        string
	DefaultValue    interface{}
}

Field model field, just using in model time for now

type FindAndCountResult

type FindAndCountResult struct {
	Total int64
	Data  []bson.Raw
}

FindAndCountResult data struct for FindAndCount

type FindOption

type FindOption struct {
	options.FindOptions
	// contains filtered or unexported fields
}

FindOption goose custom FindOption extends mongo.options.FindOption

type Model

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

Model Model class

func NewModel

func NewModel(collectionName string, curValue interface{}) *Model

NewModel new a Model class

func (*Model) BulkWrite

func (model *Model) BulkWrite(models []mongo.WriteModel) (*mongo.BulkWriteResult, error)

BulkWrite insert batch records

func (*Model) DeleteMany

func (model *Model) DeleteMany(filter interface{}) (*mongo.DeleteResult, error)

DeleteMany delete batch records

func (*Model) DeleteOne

func (model *Model) DeleteOne(filter interface{}) (*mongo.DeleteResult, error)

DeleteOne delete record by filter

func (*Model) DeleteOneByID

func (model *Model) DeleteOneByID(id string) (*mongo.DeleteResult, error)

DeleteOneByID delete record by id

func (*Model) Find

func (model *Model) Find(filter interface{}) (result []bson.M, err error)

Find support populate find operation

func (*Model) FindAndCount

func (model *Model) FindAndCount(filter bson.M) (*FindAndCountResult, error)

FindAndCount find data and number count

func (*Model) FindOne

func (model *Model) FindOne(filter interface{}) (result *mongo.SingleResult, err error)

FindOne find data by filter

func (*Model) FindOneAndUpdate

func (model *Model) FindOneAndUpdate(filter interface{}, updates interface{}) (*mongo.SingleResult, error)

FindOneAndUpdate find one and update by filter

func (*Model) FindOneByID

func (model *Model) FindOneByID(id string) (*mongo.SingleResult, error)

FindOneByID find data by model.primaryKey

func (*Model) FindOneByIDAndUpdate

func (model *Model) FindOneByIDAndUpdate(id string, updates interface{}) (*mongo.SingleResult, error)

FindOneByIDAndUpdate find one and update by id

func (*Model) InsertOne

func (model *Model) InsertOne(v interface{}) (string, error)

InsertOne insert data into collection

func (*Model) Limit

func (model *Model) Limit(num int64) *Model

Limit set limit for find

func (*Model) Populate

func (model *Model) Populate(collectionName string) *Model

Populate populate data from other collection

func (*Model) Save

func (model *Model) Save() error

Save insert or update model

func (*Model) Skip

func (model *Model) Skip(num int64) *Model

Skip set skip for find

func (*Model) SoftDeleteMany

func (model *Model) SoftDeleteMany(filter interface{}) (*mongo.UpdateResult, error)

SoftDeleteMany soft delete batch record

func (*Model) SoftDeleteOne

func (model *Model) SoftDeleteOne(filter interface{}) (*mongo.UpdateResult, error)

SoftDeleteOne soft delete single record

func (*Model) UpdateMany

func (model *Model) UpdateMany(filter interface{}, updates interface{}) (*mongo.UpdateResult, error)

UpdateMany update batch records

type ModelTime

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

ModelTime model time

type Relation

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

Relation model relation for populate

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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