gmgo

package module
v0.0.0-...-adc4b4d Latest Latest
Warning

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

Go to latest
Published: May 9, 2017 License: MIT Imports: 6 Imported by: 0

README

gmgo

Convenient wrapper around Go's MongoDB driver Mgo

Usage:

package main

import (
	"fmt"
	"github.com/narup/gmgo"
	"log"
)

var userDB gmgo.Db

####################
type User struct {
    Name string `json:"name" bson:"name"`
    Email string `json:"email" bson:"email"`
}

// Each of your data model that needs to be persisted should implment DBObject interface
func (user User) CollectionName() string {
    return "user"
}

####################

func saveNewUser() {
   session := userDB.Session()
   defer session.Close()
   
   user := &User{Name:'Puran', Email:'puran@xyz.com'}
   user.Id = bson.NewObjectId()
   userId, err := session.Save(user)
   if err != nil {
	log.Fatalf("Error saving user : %s.\n", err)
   }

   fmt.Printf("User id %s", userId)
}

func findUser(userId string) *User {
    session := userDB.Session()
    defer session.Close()
   
    user := new(User)
    if err := session.FindByID(userId, user); err != nil {
        return nil
    }
    return user
}

//Find all users
func findAllUsers() {
    session := userDB.Session()
    defer session.Close()

    users, err := session.FindAll(gmgo.Q{}, new(User)) //Note user pointer is passed to identify the collection type etc.
    if err != nil {
    	fmt.Printf("Error fetching users %s", err)
    } else {
	for _, user := range users {
	   fmt.Println(user.Name)
        }
    }
}

func setupUserDB() {
    if userDbErr := gmgo.Setup(gmgo.DbConfig{"localhost:27017", "userdb", "", ""}); userDbErr != nil {
        
    //如果 你要带上验证的一定用下面的
    //if userDbErr := gmgo.DbConfig{HostURL:"localhost:27017",Hosts:[]string{"localhost"}, DBName: "mdb", UserName: "user", Password: "pass", Mode: 1}; userDbErr != nil {
    		log.Fatalf("Database connection error : %s.\n", userDbErr)
    		return
    }

    newDb, userDbErr := gmgo.New("userdb")
    if userDbErr != nil {
        log.Fatalf("Db connection error : %s.\n", err)
    }
    userDB = newDb
}

func main() {
    //setup Mongo database connection. You can setup multiple db connections
    setupUserDB()
    user := findUser("56596608e4b07ceddcfad96e")
    if user != nil {
    	fmt.Printf("User name:%s\n", user.Name)
    } else {
	fmt.Printf("Couldn't find user")
    }
	
    findAllUsers()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Setup

func Setup(dbConfig DbConfig) error

Setup the MongoDB connection based on passed in config. It can be called multiple times to setup connection to multiple MongoDB instances.

Types

type Db

type Db struct {
	Config DbConfig
	// contains filtered or unexported fields
}

Db represents database connection which holds reference to global session and configuration for that database.

func Get

func Get(dbName string) (Db, error)

Get creates new database connection

func (Db) Session

func (db Db) Session() *DbSession

Session creates the copy of the main session

type DbConfig

type DbConfig struct {
	HostURL, DBName, UserName, Password string
	Hosts                               []string
	Mode                                int
}

DbConfig represents the configuration params needed for MongoDB connection

type DbSession

type DbSession struct {
	Session *mgo.Session
	// contains filtered or unexported fields
}

DbSession mgo session wrapper

func (*DbSession) Clone

func (s *DbSession) Clone() *DbSession

Clone returns the clone of current DB session. Cloned session uses the same socket connection

func (*DbSession) Close

func (s *DbSession) Close()

Close closes the underlying mgo session

func (*DbSession) Exists

func (s *DbSession) Exists(query Q, document Document) (bool, error)

Exists check if the document exists for given query

func (*DbSession) Find

func (s *DbSession) Find(query Q, document Document) error

Find the data based on given query

func (*DbSession) FindAll

func (s *DbSession) FindAll(query Q, document Document) (interface{}, error)

FindAll returns all the documents based on given query

func (*DbSession) FindAllWithFields

func (s *DbSession) FindAllWithFields(query Q, fields []string, document Document) (interface{}, error)

FindAllWithFields returns all the documents with given fields based on a given query

func (*DbSession) FindByID

func (s *DbSession) FindByID(id string, result Document) error

FindByID find the object by id. Returns error if it's not able to find the document. If document is found it's copied to the passed in result object.

func (*DbSession) FindByRef

func (s *DbSession) FindByRef(ref *mgo.DBRef, document Document) error

FindByRef finds the document based on given db reference.

func (*DbSession) FindWithLimit

func (s *DbSession) FindWithLimit(limit int, query Q, document Document) (interface{}, error)

FindWithLimit find the doucments for given query with limit

func (*DbSession) Pipe

func (s *DbSession) Pipe(pipeline interface{}, document Document) *mgo.Pipe

Pipe returns the pipe for a given query and document

func (*DbSession) ReadFile

func (s *DbSession) ReadFile(id, prefix string, file *File) error

ReadFile read file based on given id

func (*DbSession) Remove

func (s *DbSession) Remove(query Q, document Document) error

Remove removes the given document type based on the query

func (*DbSession) RemoveAll

func (s *DbSession) RemoveAll(query Q, document Document) error

RemoveAll removes all the document matching given selector query

func (*DbSession) Save

func (s *DbSession) Save(document Document) error

Save inserts the given document that represents the collection to the database.

func (*DbSession) SaveFile

func (s *DbSession) SaveFile(file File, prefix string) (string, error)

SaveFile saves the given file in a gridfs

func (*DbSession) Update

func (s *DbSession) Update(selector Q, document Document) error

Update updates the given document based on given selector

func (*DbSession) UpdateFieldValue

func (s *DbSession) UpdateFieldValue(query Q, collectionName, field string, value interface{}) error

UpdateFieldValue updates the single field with a given value for a collection name based query

type Document

type Document interface {
	CollectionName() string
}

Document interface implemented by structs that needs to be persisted. It should provide collection name, as in the database. Also, a way to create new object id before saving.

type File

type File struct {
	ID          string
	Name        string
	ContentType string
	ByteLength  int
	Data        []byte
}

File file representation

type Q

type Q map[string]interface{}

Q query representation to hide bson.M type to single file

Jump to

Keyboard shortcuts

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