Dra*_*ag0 5 javascript mongoose mongodb node.js objectid
我的网址目前看起来像这样:
http://www.sitename.com/watch?companyId=507f1f77bcf86cd799439011&employeeId=507f191e810c19729de860ea&someOtherId=.....
Run Code Online (Sandbox Code Playgroud)
所以,正如你所看到的,它变得非常长,非常快.我在考虑缩短这些ObjectIds.想法是我应该为我的数据库中的每个模型添加名为"shortId"的新字段.所以不要:
var CompanySchema = mongoose.Schema({
/* _id will be added automatically by mongoose */
name: {type: String},
address: {type: String},
directorName: {type: String}
});
Run Code Online (Sandbox Code Playgroud)
我们会这样:
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},
});
Run Code Online (Sandbox Code Playgroud)
我找到了这样做的方法:
// Encode
var b64 = new Buffer('47cc67093475061e3d95369d', 'hex')
.toString('base64')
.replace('+','-')
.replace('/','_')
;
// -> shortID is now: R8xnCTR1Bh49lTad
Run Code Online (Sandbox Code Playgroud)
但我仍然认为它可能更短.
另外,我发现这个npm模块:https://www.npmjs.com/package/short-mongo-id 但我没有看到它被过多使用,所以我不知道它是否可靠.
有人有什么建议吗?
Dra*_*ag0 14
我最终这样做:
安装shortId模块(https://www.npmjs.com/package/shortid)现在,当您将对象保存在数据库中时,需要以某种方式将这个shortId粘贴到您的对象上.我发现最简单的方法是将这个功能附加到名为"save()"的mongoose函数的末尾(如果你宣传你的模型,则添加"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);
};
Run Code Online (Sandbox Code Playgroud)
所以你基本上每个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}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3264 次 |
| 最近记录: |