From 992d41374f715c90e23406b0e8e72f6ce07805df Mon Sep 17 00:00:00 2001 From: Mazyar Date: Mon, 22 Jun 2026 23:38:57 +0330 Subject: [PATCH] Update company entity and repository for document file ID handling - Modified the `DocumentFileIDs` field in the `Company` struct to ensure it is always persisted in BSON format, enhancing data consistency. - Implemented logic in the `Update` method of the `companyRepository` to clear document file IDs when the slice is empty, ensuring accurate database updates. - Added logging for errors encountered while clearing document file IDs, improving error tracking and debugging capabilities. This update enhances the management of document file IDs within the company domain, ensuring proper handling and persistence in the database. --- internal/company/entity.go | 2 +- internal/company/repository.go | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/internal/company/entity.go b/internal/company/entity.go index 171b9dd..24ecbd1 100644 --- a/internal/company/entity.go +++ b/internal/company/entity.go @@ -51,7 +51,7 @@ type Company struct { Email *string `bson:"email,omitempty" json:"email,omitempty"` // File references stored in GridFS - DocumentFileIDs []string `bson:"document_file_ids,omitempty" json:"document_file_ids,omitempty"` + DocumentFileIDs []string `bson:"document_file_ids" json:"document_file_ids,omitempty"` // Tags for categorization and search Tags *CompanyTags `bson:"tags,omitempty" json:"tags,omitempty"` diff --git a/internal/company/repository.go b/internal/company/repository.go index 7f4778e..dd3cdd5 100644 --- a/internal/company/repository.go +++ b/internal/company/repository.go @@ -169,6 +169,8 @@ func (r *companyRepository) Update(ctx context.Context, company *Company) error // Set updated timestamp using Unix timestamp company.SetUpdatedAt(time.Now().Unix()) + clearDocuments := company.DocumentFileIDs != nil && len(company.DocumentFileIDs) == 0 + // Use ORM to update company err := r.ormRepo.Update(ctx, company) if err != nil { @@ -179,6 +181,23 @@ func (r *companyRepository) Update(ctx context.Context, company *Company) error return err } + // BSON omitempty can skip empty slices in $set, so persist an explicit empty array. + if clearDocuments { + _, err = r.collection.UpdateOne(ctx, bson.M{"_id": company.ID}, bson.M{ + "$set": bson.M{ + "document_file_ids": []string{}, + "updated_at": company.UpdatedAt, + }, + }) + if err != nil { + r.logger.Error("Failed to clear company document file IDs", map[string]interface{}{ + "error": err.Error(), + "company_id": company.ID, + }) + return err + } + } + r.logger.Info("Company updated successfully", map[string]interface{}{ "company_id": company.ID, "name": company.Name,