doumiang2297 2016-10-10 21:03
浏览 110
已采纳

mgo collection.Find(nil).All(&users)不起作用

I'm having the next issue.. I can't get all records from my mongo database (running in a docker containner), here is my really simple code:

type User struct {
    Email string `json:"email" bson:"email"`
    Pass  string `json:"pass" bson:"pass"`
}

session := dbConnect()
collection := session.DB("my_db").C("users")
var users []User
err := collection.Find(nil).All(&users)
if err != nil {
    log.Fatal("Mongo collection find fail: ", err)
}
fmt.Println("Results >> ", err)

The thing is "err" returns <nil>. Something weird is that inserting documents on the database actually works. Thank you!

  • 写回答

1条回答 默认 最新

  • douchenzhan3050 2016-10-11 08:51
    关注

    There is no issue with your code, but the last line fmt.Println("Results >> ", err), shouldn't it be fmt.Println("Results >> ", users) ?

    Also you can check if collection is not empty and fields are correct by using interface

    session := dbConnect()
        collection := session.DB("my_db").C("users")
        var v []interface{}
        err := collection.Find(nil).All(&v)
        if err != nil {
            log.Fatal("Mongo collection find fail: ", err)
        }
        fmt.Println("Results >> ", v)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题