我正在尝试将数据从 DB ( Mongo ) 映射到 slice in go ,如果我返回简单的 []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 }, ... ]
,但实际输出是[{ 名称:“someOrg”,ID:“someId”},{名称:“someOrg”,ID:“someId”},...]
我正在使用 bongo
包。
请您参考如下方法:
应用程序在循环的每次迭代中附加相同的 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
}