55 "errors"
66
77 "go.mongodb.org/mongo-driver/bson/primitive"
8+ "go.mongodb.org/mongo-driver/mongo/options"
89
910 "github.com/ONSdigital/dis-migration-service/config"
1011 "github.com/ONSdigital/dis-migration-service/domain"
@@ -43,10 +44,12 @@ func (m *Mongo) createJobNumberCounter(ctx context.Context) (domain.Counter, err
4344// in mongoDB, and then returns it
4445func (m * Mongo ) GetNextJobNumberCounter (ctx context.Context ) (* domain.Counter , error ) {
4546 var jobNumberCounter domain.Counter
47+
48+ // Configure FindOneAndUpdate to return the updated document (after increment)
4649 err := m .Connection .Collection (m .ActualCollectionName (config .CountersCollectionTitle )).FindOneAndUpdate (ctx ,
4750 bson.M {"counter_name" : "job_number_counter" }, bson.D {
4851 {Key : "$inc" , Value : bson.D {primitive.E {Key : "counter_value" , Value : 1 }}},
49- }, & jobNumberCounter )
52+ }, & jobNumberCounter , mongodriver . ReturnDocument ( options . After ) )
5053
5154 if err != nil {
5255 if errors .Is (err , mongodriver .ErrNoDocumentFound ) {
@@ -56,9 +59,9 @@ func (m *Mongo) GetNextJobNumberCounter(ctx context.Context) (*domain.Counter, e
5659 if err != nil {
5760 log .Info (ctx , "error creating job number counter" )
5861 return nil , err
59- } else {
60- return & jobNumberCounter , nil
6162 }
63+ // After creating the counter with value 0, increment it to 1 and return
64+ return m .GetNextJobNumberCounter (ctx )
6265 }
6366 return nil , appErrors .ErrInternalServerError
6467 }
0 commit comments