How to add an element to an array using the values already stored? I am using UpdateOne() with $push and $each. If the values are sent manually, it does so, but not if I try to retrieve them from the structures in the execution.
Defined structures:
type paidticket struct {
TipoDoc string `bson:"tipodoc"`
FechaDoc time.Time `bson:"fechadoc"`
Sucursal int `bson:"sucursal"`
NumCaja int `bson:"numcaja"`
NumCom int `bson:"numcom"`
LetraIva string `bson:"letraiva"`
Monto float32 `bson:"importe"`
Moneda string `bson:"moneda"`
FormaPago string `bson:"formapago"`
TipoCambio float32 `bson:"tipocambio"`
}
type item struct {
Cliente string `bson:"_id"`
Nombre string `bson:"nombre"`
Tickets []paidticket `bson:"pagos"`
Recibido time.Time `bson:"recibido"`
}
My code in GO:
func (r *ItemRepository) Save(modelItem *entities.Item) error {
item := r.convertModel2Item(modelItem)
fmt.Println("item: ", item, "paidticket: ", paidticket{})
data := paidticket{
TipoDoc: "PP",
FechaDoc: time.Now(),
Sucursal: 25,
NumCaja: 32,
NumCom: 4388,
LetraIva: "B",
Monto: 7000,
Moneda: "ARS",
FormaPago: "EF",
TipoCambio: 1,
}
col := r.client.Database(r.databaseName).Collection(itemCollectionName)
opt := options.UpdateOptions{
Upsert: &theTruth,
}
filter := bson.M{"_id": modelItem.Cliente}
addElem := bson.M{"$push": bson.M{"pagos": bson.M{"$each": []paidticket{data}}}}
ctx, _ := context.WithTimeout(context.Background(), time.Second*5) // antes era: ctx, cancel
_, err := col.UpdateOne(ctx, filter, &addElem, &opt)
return err
}
I'm learning about handling variables, structures, pointers and I think I'm not writing the code correctly.
Result is: Example