为URI(JavaScript / NodeJS)生成唯一的string

我正在写一个网站,我想为每篇文章生成一个随机链接。 我想链接是唯一的。 但是我也想确保我能够拥有10万条具有独特链接的文章。 (我正在使用MongoDB – mongoose)。 示例链接:qw463253qqrASd。 符号最大数量:15。

var PostSchema = new Schema({ title: String, url: {type: String, unique: true, default: (() => { let gen = "", possible = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789"; range(100).forEach((value, index) => gen += possible.charAt(Math.floor(Math.random() * possible.length))); return gen; })()}, ... }); 

PS:我有一个函数可以产生数组。

看看mongoose短裤模块。

 var ShortId = require('mongoose-shortid'); var PostSchema = new Schema({ title: String, url: { type : ShortId, len : 15, base : 62, alphabet: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', retries : 4, // Four retries on collision index : true }, }); 

关于这个模块的一些警告,虽然:

  • 它没有保持非常积极的;
  • 它目前拒绝与mongoose版本4.x或更高的工作;
  • 它产生的ID倾向于以一个,两个或三个零开始。

也许还有其他类似的模块。