Nodejs generate short unique alphanumeric

前端 未结 6 644
借酒劲吻你
借酒劲吻你 2021-01-30 23:55

I would like to generate a short unique alphanumeric value to be used as confirmation codes for online purchases. I\'ve looking into https://github.com/broofa/node-uuid but the

6条回答
  •  迷失自我
    2021-01-31 00:36

    Install shortId module (https://www.npmjs.com/package/shortid). By default, shortid generates 7-14 url-friendly characters: A-Z, a-z, 0-9, _- but you can replace - and _ with some other characters if you like. Now you need to somehow stick this shortId to your objects when they're being saved in the database. Best way is to stick them in Schema like this:

    var shortId = require('shortid');
    var PurchaseConfirmationSchema = mongoose.Schema({
      /* _id will be added automatically by mongoose */
      shortId: {type: String, unique: true, default: shortId.generate}, /* WE SHOULD ADD THIS */
      name: {type: String},
      address: {type: String}
    });
    

    I already answered similiar question to myself over here:

    Shorten ObjectId in node.js and mongoose

提交回复
热议问题