Javascript 缩短node.js和mongoose中的ObjectId
我的URL目前看起来像这样:Javascript 缩短node.js和mongoose中的ObjectId,javascript,node.js,mongodb,mongoose,objectid,Javascript,Node.js,Mongodb,Mongoose,Objectid,我的URL目前看起来像这样: http://www.sitename.com/watch?companyId=507f1f77bcf86cd799439011&employeeId=507f191e810c19729de860ea&someOtherId=..... 所以,正如你所看到的,它变得相当长,相当快。 我在考虑缩短这些对象。 我的想法是,我应该向数据库中的每个模型添加名为“shortId”的新字段。因此,我们没有: var CompanySchema = mongoo
http://www.sitename.com/watch?companyId=507f1f77bcf86cd799439011&employeeId=507f191e810c19729de860ea&someOtherId=.....
所以,正如你所看到的,它变得相当长,相当快。
我在考虑缩短这些对象。
我的想法是,我应该向数据库中的每个模型添加名为“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
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);
};
但我还是觉得可以再短一点
此外,我还发现了这个npm模块:
但我看不出它被用得太多,所以我不知道它是否可靠
有人有什么建议吗?我最后是这样做的:
// Encode
var b64 = new Buffer('47cc67093475061e3d95369d', 'hex')
.toString('base64')
.replace('+','-')
.replace('/','_')
;
// -> shortID is now: R8xnCTR1Bh49lTad
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);
};
安装shortId模块()
现在,当对象保存在数据库中时,您需要以某种方式将此shortId粘贴到对象上。我发现最简单的方法是在mongoose名为“save()”(或者“saveAsync()”(如果您推荐了您的模型)的函数末尾附加此功能。您可以这样做:
// Encode
var b64 = new Buffer('47cc67093475061e3d95369d', 'hex')
.toString('base64')
.replace('+','-')
.replace('/','_')
;
// -> shortID is now: R8xnCTR1Bh49lTad
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。就这样
编辑:
另外,我发现在模式中,您可以像这样做得更好、更干净
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库。文档也很好:所有现有模块都使用64个字符的表进行转换。所以他们必须在字符集中使用“-”和“u”字符。当您通过twitter或facebook共享短url时,它会导致url编码。所以要小心。 我使用自己的短id模块来解决这个问题,因为它使用字母数字集进行转换。
祝你成功 您好,shortId是否会在服务器重新启动后给出唯一字符串?@NallaSrinivas-是的,它会。他们的npm站点上有文档