eversun
eversun

Reputation: 63

generate auto increment order_id in a collection

so I have store collection like following:


     { 
         "_id" : ObjectId("5cd4c45492e22458d9570841"), 
         "store_id" : ObjectId("5cd4c45492e22458d9570840"), 
         "create_dt" : ISODate("2019-05-10T00:22:44.000+0000"), 
         "update_dt" : ISODate("2019-06-03T19:35:00.000+0000"), 
         "order_id_counter" : NumberInt(1001)
     }

each store has one record which contains a unique store_id, I need to build a function getOrderId(store_id) to automatically return the generated easy to remember unique order_id each time the function is invoked, each call will automatically increase the order_id_counter value by 1 for that store's record(each store will have it's own order_id_counter, it has different value for each store). I also want the operation be atom.

how to write the code for the above function? what's the most efficient way?

Upvotes: 0

Views: 364

Answers (2)

klhr
klhr

Reputation: 3380

One approach to generating a unique, incrementing number in mongo would be creating a separate collection with {store_id, current_count} & using a findAndModify operations with $inc to increment the counter & return the document. In this case, there's no guarantee that once a number is generated that the corresponding order will successfully be created, so you may end up with gaps.

Another approach would be creating a unique index on the combination {store_id: 1, order_id_counter: 1} Inserting new orders would sometimes fail and need to be retried.

Upvotes: 0

Sourav De
Sourav De

Reputation: 99

const Autoidmodule= {
    autogenerateId:(request,callback)=>{
        console.log(request)
        var milliseconds = new Date().getTime();
        const finalId=request+milliseconds;
        callback(null,finalId)

    },
}
module.exports = Autoidmodule;
...........................................................

let type = "STORE";
let autouserid;
AutogenerateIdcontroller.autogenerateId(type, (err, data) => {
    autouserid = data;
})

Upvotes: -1

Related Questions