Search code examples
mongodbgomgo

how to fetch the unknown mongo doc via mgo


Here is the piece of code that is trying to fetch all the docs from the mongodb.

func fetchAll(db *mgo.Database) map[string]interface {
    var msg map[string]interface{}
    err := db.C("msg").Find(nil).All(&msg)
    if err != nil {
        panic(err)
    }
    return msg
}

I got the error: syntax error: unexpected var

What is wrong here? And is there a better way to fetch the arbitrary mongo docs via mgo?

thanks


Solution

  • First, fix the syntax error:

    func fetchAll(db *mgo.Database) map[string]interface{} {
        var msg map[string]interface{}
        err := db.C("msg").Find(nil).All(&msg)
        if err != nil {
            panic(err)
        }
       return msg
    }
    

    Note the {} in the function return type declaration.

    But there's more. All() retrieves all documents from the result set to a slice. Change the return type to a slice of maps:

    func fetchAll(db *mgo.Database) []map[string]interface{} {
        var msgs []map[string]interface{}
        err := db.C("msg").Find(nil).All(&msgs)
        if err != nil {
            panic(err)
        }
       return msgs
    }
    

    While we are at it, let's return the error instead of panicking.

    func fetchAll(db *mgo.Database) ([]map[string]interface{}, error) {
        var msgs []map[string]interface{}
        err := db.C("msg").Find(nil).All(&msgs)
        return msgs, err
    }