缩短node.js和mongoose中的ObjectId
我的url现在是这样的:
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}, });
我find了一个这样做的方法:
// Encode var b64 = new Buffer('47cc67093475061e3d95369d', 'hex') .toString('base64') .replace('+','-') .replace('/','_') ; // -> shortID is now: R8xnCTR1Bh49lTad
但我仍然认为这可能会更短。
另外,我发现这个NPM模块: https ://www.npmjs.com/package/short-mongo-id,但我没有看到它被用得太多,所以我不能告诉它是否可靠。
任何人有任何build议?
我结束了这样做:
安装shortId模块( https://www.npmjs.com/package/shortid )现在,您需要以某种方式将这个shortId粘贴到数据库中的对象。 我发现最简单的方法是将这个function附加到mongoose函数名为“save()”(或“saveAsync()”)的函数上,如果你的模型被promisified的话。 你可以这样做:
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()函数附加这个function来添加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} });
所有现有的模块使用64个字符表进行转换。 所以他们必须在字符集中使用“ – ”和“_”字符。 当您通过Twitter或Facebook分享短的url时,它会导致url编码。 所以要小心。 我使用我自己的短ID模块id-较短 ,从这个问题,因为它使用字母数字集转换。 祝你成功!