I am trying to create a new database in mongodb using revel framework and mgo driver. Here's my code in --> src/myapp/app/db/mgo.go
package db
import (
"fmt"
"gopkg.in/mgo.v2"
)
var Session *mgo.Session
var Users *mgo.Collection
func Init(url, dbname string) {
var err error
Session,err = mgo.Dial(url)
if err!=nil{
panic(err)
}
Session.SetMode(mgo.Monotonic, true)
Users = Session.DB(dbname).C("users")
}
and here's the code from where the program runs --> src/myapp/app/controllers/app.go
package controllers
import (
"github.com/revel/revel"
"myapp/app/db"
)
type App struct {
*revel.Controller
}
func (c App) Hello() revel.Result{
db.Init("127.0.0.1", "mydb")
return c.Render()
}
The problem is I am not able to create a database by these two parts of separate files of code, whereas when I merge them in one (i.e. just app.go) then it works well. Here's the code that works in --> src/myapp/app/controllers/app.go
package controllers
import (
"github.com/revel/revel"
"gopkg.in/mgo.v2"
)
type App struct {
*revel.Controller
}
func (c App) Hello() revel.Result{
session,err:=mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
d:=session.DB("mydb").C("anydata")
return c.Render()
}
So I would like someone to help me in correcting my first two parts of code
you have access to db.Session
and db.Users
from controllers/app.go
package controllers
import (
"github.com/revel/revel"
"myapp/app/db"
)
type App struct {
*revel.Controller
}
func init() {
db.Init("127.0.0.1", "mydb")
}
func (c App) Hello() revel.Result{
//there use db
db.Session.Find(...)
return c.Render()
}