如何解决:Golang的“追加”方法将相同的元素压入切片

时间:2019-06-24 15:26:00

标签: mongodb go

我正在尝试将数据库(Mongo)中的数据映射到go中的slice中,并且如果我返回简单的[]string,一切都可以正常工作,但是如果我将类型更改为[]*models.Organization,则代码将返回slice相同的元素。

func (os *OrganizationService) GetAll() ([]*models.Organization, error) {
    var organizations []*models.Organization
    results := os.MongoClient.Collection("organizations").Find(bson.M{})
    organization := &models.Organization{}
    for results.Next(organization) {
        fmt.Println(organization)
        organizations = append(organizations, organization)
    }
    return organizations, nil
}


我希望输出[{ Name: "someOrg", ID: "someId" },{ Name: "someOrg2", ID: "someID }, ... ],但实际输出是[{ Name: "someOrg", ID: "someId" },{ Name: "someOrg", ID: "someId" }, ... ]

我正在使用bongo软件包。

1 个答案:

答案 0 :(得分:2)

应用程序在循环中的每次迭代中都附加相同的organization值。通过在循环内创建新值来解决。

func (os *OrganizationService) GetAll() ([]*models.Organization, error) {
    var organizations []*models.Organization
    results := os.MongoClient.Collection("organizations").Find(bson.M{})
    organization := &models.Organization{}
    for results.Next(organization) {
        fmt.Println(organization)
        organizations = append(organizations, organization)
        organization = &models.Organization{} // new value for next iteration
    }
    return organizations, nil
}