What is better: global pointer to mongo database or create new connection when needed

56 views
Skip to first unread message

Luke

unread,
Aug 3, 2016, 12:54:08 PM8/3/16
to mgo-users
Can somebody help me to decide which solution is better:

1. Have one global pointer to the database that is created on init(), e.g. 

var GlobalMongoDB *mgo.Database

func NewConnection(MY_HOST, MY_DB, USER, PASS) {
	session, _ := mgo.Dial(MY_HOST)
	session.SetMode(mgo.Monotonic, true)
	db := session.DB(MY_DB)
	db.Login(USER, PASS)
	return db
}

func init() {
   GlobalMongoDB = NewConnection(MY_HOST, MY_DB, USER, PASS)
}

2. Call NewConnection every time I need connection the the database

Gustavo Niemeyer

unread,
Aug 3, 2016, 1:41:53 PM8/3/16
to mgo-...@googlegroups.com
Definitely don't reconnect every time. That undoes many of the benefits the driver buys you.

The actual best is to do the usual thing: make sure functions and values get the context they need to do their proper work. No globals.

Of course, unless you're writing a 20 lines hack. In which case, anything will do. 


--
You received this message because you are subscribed to the Google Groups "mgo-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mgo-users+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

Luke

unread,
Aug 3, 2016, 4:39:53 PM8/3/16
to mgo-users
makes sense, thank you
Reply all
Reply to author
Forward
0 new messages