Iris: MongoDB + Iris + Mvc

Created on 1 Feb 2018  ·  9Comments  ·  Source: kataras/iris

Hello! I would like to use the MongoDB database, are there any examples of ready-made projects using mongodb? I found in the examples: https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c. But I would like a full project with the structure:
├── controllers
├── models
└── views
I can not understand how best to connect iris and mongo.

good first issue support

Most helpful comment

Very nice! That's how I want to see you coding, using interfaces for services and mapping them to your controllers, so you can make testing even easier and provide more back-end services types for storing process, good job @Jinfaa!

All 9 comments

Hello @Jinfaa, it's quite easy to do that with MVC architecture in Iris, although I have to warn you that the library (go-mgo/mgo) you're using is UNMAINTAINED.

Based on the article you sent:

import (
    "gopkg.in/mgo.v2"

    "github.com/kataras/iris"
         "github.com/kataras/iris/mvc"
)

// web/controllers/my_controller.go
type MyController struct {
        DB *mgo.Database
}

func (c *MyController) Get() {
         // c.DB...
}

// ...

// web/main.go
func main() {
        app := iris.New()

    // Database connection
    session, err := mgo.Dial("localhost")
    if nil != err {
        panic(err)
        }
        defer session.Close()
        session.SetMode(mgo.Monotonic, true)
        db := session.DB("car-db")

        controllers := mvc.New(app)
        // Registers 'db' as *mgo.Database in the DB field of our controller(s)
        controllers.Register(db)

        controllers.Handle(&MyController{})

         // ...
}

For a full structures you can view the structing and the mvc/** examples, they provide a very good idea of structuring your web mvc applications with different ways, but it's always depend on your application's needs.

Don't hesitate to ask more at our chat as well!

@Jinfaa You can use this fork https://github.com/globalsign/mgo. It has completely the same API like the original unmaintained repository, also there are many bug fixes + some new stuff.

Thank for answers.
I did now like this:

type MyController struct {
        Ctx     iris.Context
    Service services.MyService
}
func main() {
        ...
        session, err := mgo.Dial("mongodb://192.168.0.133/")
    if nil != err {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)
    db := session.DB("test")

    myService := services.NewMyService(db, session)

    controller := mvc.New(app.Party("/test"))
    controller.Register(myService)
    controller.Handle(new(controllers.myController))
}



md5-bd0c00d5251beb9b99356f16af20f850



func Get(collection *mgo.Collection, id string, i interface{}) {
    collection.FindId(bson.ObjectIdHex(id)).One(i)
}



md5-eaadaa32a491eaefe11b7b54a5a56b01



func Insert(collection *mgo.Collection, i interface{}) bool {
    err := collection.Insert(i)
    return Err(err)
}



md5-a993908af1d252809d4ae291e2aaabfe



type MyService interface {
      NewMyModel(myModel model.MyModel) (error, *model.MyModel)
       ...
}

type myService struct {
    Table *mgo.Collection
}

func NewMyService(db *mgo.Database, session *mgo.Session) MyService {
    return & myService{
        Table: db.C("myCollection"),
    }
}

func (s *myService) NewMyModel(myModel model.MyModel) bool {
    if myModel.ID == "" {
        myModel.ID = bson.NewObjectId()
    }
    myModel.CreatedTime = time.Now()
    return db.Insert(s.Table, myModel)
}

Is my decision correct?

Very nice! That's how I want to see you coding, using interfaces for services and mapping them to your controllers, so you can make testing even easier and provide more back-end services types for storing process, good job @Jinfaa!

Thank you! I really like this web framework! ❤️

Hi @kataras, what if I want to implement the mgo to repository? Im currently using this structure https://github.com/kataras/iris/tree/master/_examples/mvc/overview but I failed to register the mgo in repository. What I planning to achieve is replace the current template data model source with mgo. But I a bit stuck at the part on how to register the mgo if I now using this way "repo := repositories.NewMovieRepository(datasource.Users)". Could you guide me the way to achieve this

Hey @dunchaseme I don't quite understand, you can .Register anything that you want to be binded, if a controller(or even a controller's function) in the same mvc app accepts a field with the same type as the Register's object then it works, you don't have to do anything special, you can do the same as the examples shown, it doesn't care if it's a database connection or anything.

@kataras How to declare the deferring db closing? If I register a db service in the party of the route, and these codes are in handler function, not in main function how can I close db safely?

You can register a close handler when the program is terminated by ctrl/cmd+c for example with iris.RegisterOnInterrupt(func(){ db.Close()})

Was this page helpful?
0 / 5 - 0 ratings