我正在尝试将数据从 DB ( Mongo ) 映射到 go 中的切片,如果我返回简单,则一切正常,[]string但如果我将类型更改[]*models.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) } return organizations, nil}我期望输出[{ Name: "someOrg", ID: "someId" },{ Name: "someOrg2", ID: "someID }, ... ],但实际输出是 [{ Name: "someOrg", ID: "someId" },{ Name: "someOrg", ID: "someId" }, ... ]我正在使用bongo包。
1 回答
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
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
}
- 1 回答
- 0 关注
- 123 浏览
添加回答
举报
0/150
提交
取消