1

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

  • This example shows push with one item and multiples: https://stackoverflow.com/questions/37407476/how-to-push-in-golang-for-nested-array/37408597#37408597. In your case, you're pushing one item, correct? I think you want something like: `addElem := bson.M{"$push": bson.M{"pagos":data}}`. As written you are pushing an array, to append to the existing one. – Brian Wagner May 20 '22 at 20:04
  • Exact! thank you very much for your help! Yes, I am working to add one element to the array. Finally it was as you suggest. Thank you very much again. – Marisa Montini May 24 '22 at 18:49

0 Answers0