Wilson Wang
Wilson Wang

Reputation: 111

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

Upvotes: 0

Views: 157

Answers (1)

Simon Fox
Simon Fox

Reputation: 6425

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
}

Upvotes: 4

Related Questions