繁体   English   中英

缩短 node.js 和 mongoose 中的 ObjectId

[英]Shorten ObjectId in node.js and mongoose

目前我的网址如下所示:

http://www.sitename.com/watch?companyId=507f1f77bcf86cd799439011&employeeId=507f191e810c19729de860ea&someOtherId=.....

所以,正如你所看到的,它变得非常长,非常快。 我正在考虑缩短这些 ObjectIds。 想法是我应该向数据库中的每个模型添加名为“shortId”的新字段。 所以,而不是:

var CompanySchema = mongoose.Schema({
  /* _id will be added automatically by mongoose */
  name:         {type: String},
  address:      {type: String},
  directorName: {type: String}
});

我们会有这个:

var CompanySchema = mongoose.Schema({
  /* _id will be added automatically by mongoose */
  shortId:      {type: String}, /* WE SHOULD ADD THIS */
  name:         {type: String},
  address:      {type: String},
  directorName: {type: String},
});

我找到了一种方法来做到这一点:

// Encode
var b64 = new Buffer('47cc67093475061e3d95369d', 'hex')
  .toString('base64')
  .replace('+','-')
  .replace('/','_')
;
// -> shortID is now: R8xnCTR1Bh49lTad

但我仍然认为它可以更短。

另外,我发现了这个 npm 模块: https ://www.npmjs.com/package/short-mongo-id 但我没有看到它被使用得太多,所以我不知道它是否可靠。

有人有什么建议吗?

我最终这样做了:

安装 shortId 模块 ( https://www.npmjs.com/package/shortid ) 现在,当它们保存在数据库中时,您需要以某种方式将此 shortId 粘贴到您的对象上。 我发现最简单的方法是在猫鼬的名为“save()”(或“saveAsync()”,如果你承诺你的模型)的函数的末尾附加这个功能。 你可以这样做:

var saveRef = Company.save;
Company.save = function() {
  var args = Array.prototype.slice.call(arguments, 0);
  // Add shortId to this company
  args[0].shortId = shortId.generate();
  return saveRef.apply(this, args);
};

所以你基本上只是在每个 Model.save() 函数中附加这个功能来添加 shortId。 就是这样。

编辑:另外,我发现你可以像这样直接在 Schema 中做得更好更干净。

var shortId = require('shortid');
var CompanySchema = 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},
  directorName: {type: String}
});

编辑:现在您可以使用性能更高且经过优化的 nanoid 库。 文档也很好: https : //github.com/ai/nanoid/

所有现有模块都使用 64 个字符表进行转换。 所以他们必须在字符集中使用“-”和“_”字符。 当您通过 twitter 或 facebook 共享短网址时,它会导致网址编码。 所以要小心。 我使用我自己的短 id 模块id-shorter没有这个问题,因为它使用字母数字集进行转换。 祝你成功!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM