Good day to all! I ask for help from experienced programmers! :)

There is a similar code on node.js:

static create_user(params, callback) { let user_document = { //user_id: ВОТ_ТУТ_НАДО_СГЕНЕРИТЬ_ID, fb_id:params.fb_id||false, vk_id:params.vk_id||false, first_name:params.first_name||false, last_name:params.last_name||false, city:params.city||false }; users_collection.insert(user_document, (err, user_result)=> { console.log(user_document, user_result); callback(err, user_document); }); } 

Of course returns what is expected. But the problem is, I can not give users an id that generates mongodb ("_ id": ObjectId ("57dfec32d1703f11ac9c4500")), this is not convenient, not visual, and I don’t want to burn what database I have.

Everyone wants to use auto-increment, I have already invented several ways. But how to do it right?

    2 answers 2

      static auto_id(name, callback){ mongo_db.collection('__counters').findAndModify( { _id: name }, [], { $inc: { "inc": 1 } }, { new: true , upsert:true}, (err, response)=>{ callback(response.value.inc); } ); } 

    Found only such an "elegant" solution

      Here is a great module for you: https://www.npmjs.com/package/mongodb-autoincrement You can use the example for this link.

      • I think this option is as uncomfortable / convenient as mine. - ErrorMan