本文介绍了缩短node.js和mongoose中的ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网址目前看起来像这样:

my URLs look like this at the moment:

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

所以,你可以看到,它得到很长,非常快。
我在考虑缩短这些ObjectIds。
想法是我应该为我的数据库中的每个模型添加名为shortId的新字段。因此,而不是:

So, as you can see, it gets pretty long, pretty fast.I was thinking about shortening these ObjectIds. Idea is that I should add new field called "shortId" to every model in my database. So instead of having:

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

但我仍然认为它可能更短。

But I still think it could be shorter.

另外,我找到了这个npm模块:
但是我没有看到它被过多使用,所以我不知道它是否可靠。

Also, I found this npm module: https://www.npmjs.com/package/short-mongo-idbut I don't see it's being used too much so I can't tell if it's reliable.

任何人都有任何建议吗?

Anyone has any suggestions?

推荐答案

我最终这样做:

安装shortId模块()
现在你需要以某种方式将这个shortId粘贴到你的对象中,当它们被保存在数据库中时。我发现最简单的方法是将这个功能附加到名为save()的mongoose函数的末尾(如果你宣传你的模型,则添加saveAsync())。你可以这样做:

Install shortId module (https://www.npmjs.com/package/shortid)Now you need to somehow stick this shortId to your objects when they're being saved in the database. I found the easiest way to do this is to append this functionality on the end of mongoose's function called "save()" (or "saveAsync()" if you promisified your model). You can do it like this:

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。就是这样。

So you just basically at each Model.save() function append this functionality to add shortId. That's that.

编辑:
另外,我发现你可以在Schema中做得更好更干净。

Also, I discovered that you can do it better and cleaner like this straight in 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}
});

这篇关于缩短node.js和mongoose中的ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 19:50