mongoutils

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

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

Go to latest
Published: Aug 30, 2015 License: MIT Imports: 7 Imported by: 0

README

mongoutils.go

Helper Functions for using the Golang mgo Driver for MongoDB

The intended use of this package is to simplify some functionality. It is not meant for power users or for production. Basically, this package can be used to connect or disconnect to a MongoDB (or replica set), perform ObjectId validation, convert between ObjectId and a string, and grab limit and sort values from a form value. This package will also save the connection data to a global variable that is accessible wherever this file is imported.

Of note: when you use the connection data, you will need to "copy" the connection in order to use the pool of available connections. More about this can be found in the mgo docs.


###Functions

####Connect(servers string, database string, readPreference int, writeConcern *mgo.Safe)

  • Connect to your DB(s). Stores the session connection data into a global variable.
  • servers is a single or list of servers in "servername:port" format separated by commas and ending with a "/".
  • database is the name of your database.
  • readPreference is an mgo constant that defines how you want reads to be spread across the available servers. writeConcern` is the safety level at which MongoDB will determine if a write was successful or not. More can be found in the mgo docs.

####NoResult(input error) Checks the "error" returned from a "Find One" (mgo .One()) func to see if the error means no data was found for the query.

Ex.:

data := struct{}
err  := db.DB(DATABASE).C(COLLECTION).Find(bson.M{"username":"test@test.com"}).One(&data)
if mongoutils.NoResult(err) {
	//no results
} else {
	//handle data found or other errors
}

####GetObjectIdFromString() Gets the MongoDB BSON ObjectId representation of a hexidecimal string. Returns an error if a string cannot be converted.

####GetStringFromObjectId() Self explainatory. Use the string representation of an ObjectId for user facing tasks.

####Limit() Used if you are making API calls. Grabs a limit from a form value variable, "limit". Allows users to set limits instead of hardcoded on the back end.

####Sort() Same as Limit above but for sort fields. Only allows one field to be sorted. Name of field can start with (-) to sort in decending order.

Documentation

Index

Constants

View Source
const (
	ID_LENGTH           = 24
	LIMIT_DEFAULT_VALUE = 5
	LIMIT_RETURN_ALL    = 0
	SORT_DEFAULT        = "_id"
)

Variables

View Source
var (
	//GLOBAL SESSION DATA
	SESSION *mgo.Session

	//ERROR MESSAGES
	ErrIdBadLength = errors.New("idMustBe24CharactersLong")
	ErrIdNotHex    = errors.New("idNotHexadecimal")
	ErrNoResults   = errors.New("noResultsFound")
)

Functions

func Close

func Close()

CLOSE THE DB CONNECTION using the mgo Close() function

func Connect

func Connect(servers string, database string, readPreference int, writeConcern *mgo.Safe)

CONNECT TO DB AND SETUP WRITE CONCERN AND READ PREFERENCE servers is string of at least one server to connect to ("localhost:27017/") and should be many hosts if using a replica set database is the name of your database to connect to readPreference is an mgo consistency constant (Eventual, Monotonic, Strong) writeConcern is an mgo *Safe type saves the connected session pool to a global variable.

func GetObjectIdFromString

func GetObjectIdFromString(inputId string) (bson.ObjectId, error)

CONVERT A STRING INTO AN OBJECT ID validates the input string first and returns an error if input is not a valid string to convert in: objectId as a string out: mongo objectId and error if the input is not valid

func GetStringFromObjectId

func GetStringFromObjectId(input bson.ObjectId) string

CONVERT AN OBJECT ID INTO A STRING in: mongo objectId out: string exactly 24 characters long and hexidecimal

func Limit

func Limit(r *http.Request) int

GET A LIMIT FOR NUMBER FOR RESULTS TO RETURN FROM GET VARIABLE return the limit as an integer to use in db query 5 is the default if the limit form value is not understood a limit of 0 (zero) actually returns all results, not none gets the limit value from an http GET form value i.e. example.com?limit=10

func NoResult

func NoResult(input error) (bool, error)

CHECK IF A FIND ONE RETURNED NO RESULTS

func Sort

func Sort(r *http.Request) []string

GET A FIELD TO SORT FIND RESULTS BY FROM GET VARIABLE you can sort by one or many fields, each field name separated by a comma without whitespace you can prepend a (-) minus sign to sort in decending order example.log/?sort=birthday,-username make sure to use the value this function returns as sortOrder... (note three periods) in mgo Sort() this way mgo will apply all sorts to your query

Types

This section is empty.

Jump to

Keyboard shortcuts

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