gpt4 book ai didi

javascript - 在 node.js 和 mongoose 中缩短 ObjectId

转载 作者:IT老高 更新时间:2023-10-28 13:32:06 26 4
gpt4 key购买 nike

我的网址现在看起来像这样:

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

所以,如您所见,它变得非常长,非常快。我正在考虑缩短这些 ObjectId。想法是我应该向数据库中的每个模型添加名为“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()”,如果您 promise 您的模型)的 Mongoose 函数的末尾。你可以这样做:

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/

关于javascript - 在 node.js 和 mongoose 中缩短 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28722102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com