我正在尝试将数据库(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
软件包。
答案 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
}