Shorten ObjectId in node.js and mongoose

五迷三道 提交于 2019-12-05 10:06:14

I ended up doing it like this:

Install shortId module (https://www.npmjs.com/package/shortid) Now you need to somehow stick this shortId to your objects when they're being saved in the database. I found the easiest way to do this is to append this functionality on the end of mongoose's function called "save()" (or "saveAsync()" if you promisified your model). You can do it like this:

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);
};

So you just basically at each Model.save() function append this functionality to add shortId. That's that.

Edit: Also, I discovered that you can do it better and cleaner like this straight in 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}
});

All existing modules use 64 chars table for conversion. So they have to use '-' and '_' chars in charset. It causes url encoding when you share short url through twitter or facebook. So be careful with it. I use my own short id module id-shorter that free from this problem because it uses alpha-numeric set for converting. Wish you success!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!