1 回答

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
您正在解碼為同一個(gè)指針,因此您總是會(huì)得到一個(gè)切片,其中包含的元素的值與您上次解碼的元素的值相同。
相反,您應(yīng)該在每次迭代中初始化模型類(lèi)型的新實(shí)例,然后解碼為該實(shí)例。
result, _ := mongodb.Search(store.Time{}, ...) // pass in non-pointer type to make life easier
// ...
func Search(model interface{}, filter interface{}) (result ModelCollection, err error) {
collection := Database.Collection(resolveCollectionName(model))
var cursor *mongo.Cursor
cursor, err = collection.Find(Context, filter)
if err != nil {
log.Fatal(err)
}
for cursor.Next(Context) {
v := reflect.New(reflect.TypeOf(model)).Interface() // get a new pointer instance
if err := cursor.Decode(v); err != nil { // decode
log.Fatal(err)
}
md := reflect.ValueOf(v).Elem().Interface()
result = append(result, md) // append non-pointer value
}
return
}
- 1 回答
- 0 關(guān)注
- 137 瀏覽
添加回答
舉報(bào)