// Update replaces a product document in the database.
Update replaces a product document in the database.
// Update replaces a product document in the database .
func Update(ctx context.Context, dbConn *db.DB, id string, upd UpdateProduct, now time.Time) error {
	ctx, span := trace.StartSpan(ctx, "internal.product.Update")
	defer span.End()
	if !bson.IsObjectIdHex(id) {
		return ErrInvalidID
	}
	fields := make(bson.M)
	if upd.Name != nil {
		fields["name"] = *upd.Name
	}
	if upd.Notes != nil {
		fields["notes"] = *upd.Notes
	}
	if upd.UnitPrice != nil {
		fields["unit_price"] = *upd.UnitPrice
	}
	if upd.Quantity != nil {
		fields["quantity"] = *upd.Quantity
	}
	if upd.Family != nil {
		fields["family"] = *upd.Family
	}
	if len(fields) == 0 {
		return nil
	}
	fields["date_modified"] = now
	m := bson.M{"$set": fields}
	q := bson.M{"_id": bson.ObjectIdHex(id)}
	f := func(collection *mgo.Collection) error {
		return collection.Update(q, m)
	}
	if err := dbConn.Execute(ctx, productsCollection, f); err != nil {
		if err == mgo.ErrNotFound {
			return ErrNotFound
		}
		return errors.Wrap(err, fmt.Sprintf("db.customers.update(%s, %s)", db.Query(q), db.Query(m)))
	}
	return nil
}
func Update ( ctx context . Context , dbConn * db . DB , id string , upd UpdateProduct , now time . Time ) error { ctx , span := trace . StartSpan ( ctx , " " ) defer span . End ( ) if ! bson . IsObjectIdHex ( id ) { return ErrInvalidID } fields := make ( bson . M ) if upd . Name != nil { fields [ " " ] = * upd . Name } if upd . Notes != nil { fields [ " " ] = * upd . Notes } if upd . UnitPrice != nil { fields [ " " ] = * upd . UnitPrice } if upd . Quantity != nil { fields [ " " ] = * upd . Quantity } if upd . Family != nil { fields [ " " ] = * upd . Family } if len ( fields ) == 0 { return nil } fields [ " " ] = now m := bson . M { " " : fields } q := bson . M { " " : bson . ObjectIdHex ( id ) } f := func ( collection * mgo . Collection ) error { return collection . Update ( q , m ) } if err := dbConn . Execute ( ctx , productsCollection , f ) ; err != nil { if err == mgo . ErrNotFound { return ErrNotFound } return errors . Wrap ( err , fmt . Sprintf ( " " , db . Query ( q ) , db . Query ( m ) ) ) } return nil }
Update replaces a product document in the database.
Update replaces a product document in the database .
// If there's nothing to update we can quit early.