Hi (sorry for the cryptic subject, I'm just not sure what to even call 
this):


I think this is not strictly a mgo question, I have this simplified 
function that gets documents from a mongo instance using Iter(), I then 
loop through the results, append them to a slice []interface{} but the 
resulting new slice has the last element repeated N times, where N is the 
number of item I got from the call to Iter().

In code on gist:

https://gist.github.com/fmpwizard/a1b4cc246b5875ff6bd1fbcd71940703

pasted here:


func TestBatchInsert1(t *testing.T) {
c := session.DB("testing").C("delete")
c.DropCollection()

c.Insert(bson.M{
"name": "AAAAAAA",
"num":  1,
})

c.Insert(bson.M{
"name": "BBBBBBBB",
"num":  2,
})

iter := c.Find(nil).Iter()
//var doc interface{} //if I use this line instead of a bson.M, the "issue" 
doesn't happen
var doc bson.M
var docs []interface{}

for iter.Next(&doc) {
fmt.Printf("Pre append\n\n %+v\n\n", docs)
docs = append(docs, doc)
fmt.Printf("Post append\n\n %+v\n\n", docs)
//doc = nil //This **fixes** it but why?
}
fmt.Printf("Final\n\n %+v\n\n", docs)

err := iter.Close()
if err != nil {
fmt.Printf("Failed to close iter during copy: %s", err)
}
}


the output of all that is:

Pre append

 []

Post append

 [map[_id:ObjectIdHex("580e5758ad817545b924a2c1") name:AAAAAAA num:1]]

Pre append

 [map[_id:ObjectIdHex("580e5758ad817545b924a2c2") name:BBBBBBBB num:2]]

Post append

 [map[_id:ObjectIdHex("580e5758ad817545b924a2c2") name:BBBBBBBB num:2] 
map[_id:ObjectIdHex("580e5758ad817545b924a2c2") name:BBBBBBBB num:2]]

Final

 [map[_id:ObjectIdHex("580e5758ad817545b924a2c2") name:BBBBBBBB num:2] 
map[_id:ObjectIdHex("580e5758ad817545b924a2c2") name:BBBBBBBB num:2]]


===========================

note how the second time we print "Pre append" the docs slice has is the 
second item in it, instead of the first one:

 [map[_id:ObjectIdHex("580e5758ad817545b924a2c2") name:BBBBBBBB num:2]]

as if I appended a pointer to the docs instead the actual value of doc.

I found two ways to avoid this issue, one is to uncomment

//doc = nil //

after calling append, I just don't understand why I need to reset it.

The other is, instead of working with

var doc bson.M
var docs []interface{}

I can use

var doc interface{}
var docs []interface{}

but using 

var doc bson.M
var docs []bson.M

also shows the **issue**

Thanks.

Diego

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to