相关疑难解决方法(0)

缩短node.js和mongoose中的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模块: …

javascript mongoose mongodb node.js objectid

5
推荐指数
1
解决办法
3264
查看次数

标签 统计

javascript ×1

mongodb ×1

mongoose ×1

node.js ×1

objectid ×1