自定义mongoose id:两种方式,优点和缺点是什么?

时间:2015-07-16 15:37:09

标签: node.js mongodb express mongoose

简单用例:

让我们从这个简单的模型开始:

camera.position.z = 1000;

使用此模型,Mongo中的对象采用以下形式:

// Schema
var notebookSchema = new mongoose.Schema({
  title: {
    type: 'string',
    required: true
  }
});

不要想要这种ID。我知道有些像mongoose-short-idmongoose-hook-custom-id这样的Express中间件可以做到这一点,但我不要想要使用外部依赖。

所以,我认为有两种方法可以做到这一点:

1。使用与上面提到的lib类似的代码,如下所示:

{ _id: 558ab637cab9a2b01dae9a97,
  title:"a notebook title"
}

用法:

var mongoose = require('mongoose'),
  Schema = mongoose.Schema,
  Types = mongoose.Types,
  mongooseSave = mongoose.Model.prototype.save,
  SchemaString = mongoose.Schema.Types.String;

function CustomId (key) {
  SchemaString.call(this, key);
};

CustomId.prototype.__proto__ = SchemaString.prototype;
Schema.Types.CustomId = CustomId;
Types.CustomId = String;

mongoose.Model.prototype.save = function(callback) {
  for (field in this.schema.tree) {
    if (this.isNew && this[field] === undefined) {
      var fieldType = this.schema.tree[field];
      if (fieldType === CustomId || fieldType.type === CustomId) {
        var oid = mongoose.Types.ObjectId();
        var id = new Buffer('' + oid, 'hex').toString('base64').replace('+', '-').replace('/', '_');
        this[field] = id;
        mongooseSave.call(this, function(err, obj) {
          callback(err, obj);
        });
        return;
      }
    }
  }
  mongooseSave.call(this, callback);
};
module.exports = exports = CustomId;

2。使用插件方法,如下所示:

var mongoose = require("mongoose");
var CustomId = require('../utils/custom_id');
// Schema
var BookSchema = new mongoose.Schema({
  _id: {
    type: CustomId
  },
  title: {
    type: "string",
    required: true
  }
});

这两种方法运作良好,我知道没有#34;官方神奇的标准化"方式,但你能告诉我你的选择和原因(正反两方面)

0 个答案:

没有答案