dtebrq0245 2013-04-15 09:35
浏览 42
已采纳

如何将MongoDB数据库传递给GO例程?

I'm new to Go and I'm trying to write a simple program that iterates over all users in the MongoDB database and for each user iterates over all of his posts, using the 'mgo' package.

package main

import (
    "fmt"
    "labix.org/v2/mgo"
    "labix.org/v2/mgo/bson"
)

type User struct {
    Id string
    Email string
}

type Post struct {
    Id string
    Description string
}

func handleUser(db *mgo.Database, user *User) {
    fmt.Println("ID: ", user.Id, " EMAIL: ", user.Email)

    result := Post{}

    iter := db.C("posts").Find(bson.M{"user_id": user.Id}).Iter()

    for iter.Next(&result) {
        fmt.Println("POST ID: ", result.Id, " POST DESCRIPTION: ", result.Description)
    }
}

func main() {
    session, err := mgo.Dial("localhost")

    if err != nil {
        panic(err)
    }

    defer session.Close()

    db := session.DB("mydb")

    result := User{}

    iter := db.C("users").Find(nil).Iter()
    for iter.Next(&result) {
        handleUser(db, &result)
    }   
}

this is working just fine, but if I try to change the call to handleUser(db, &result) to go handleUser(db, &result) the second query inside handleUser doesn't do anything.

I suspect that the session is already closed because 'main' already finished, am I correct? if so, what is the way to handle such scenario ?

  • 写回答

1条回答 默认 最新

  • dongtan1845 2013-04-15 09:42
    关注

    You're right about the specs, they define that when main returns, all goroutines are killed:

    When the function main returns, the program exits. It does not wait for other (non-main) goroutines to complete.

    There are two options.

    • Synchronize with your goroutines at the end of main. A "done" chanel can be used or a sync.WaitGroup.

    • Where appropriate a blocking empty select statement could be used:

      select{} // Non busy block forever

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?