node.js - Custom mongoose id : two ways of doing it, what are pros and cons? -


simple use case :

let start simple model:

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

using model, objects comes in mongo in form :

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

i do not want kind of ids. know there's express middlewares mongoose-short-id or mongoose-hook-custom-id can that, do not want use external dependencies.

so, see 2 ways doing this:

1. use similar code libs mentioned above, :

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) {   (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; 

usage:

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

2. use plugin approach, :

// schema var notebookschema = new mongoose.schema({   _id: {     type: 'string'   },   title: {     type: 'string',     required: true   } });  var customidplugin = function(schema, options) {   schema.pre('save', function(next) {     var oid = ""+mongoose.types.objectid();     this._id = new buffer(oid, 'hex').tostring('base64').replace('+', '-').replace('/', '_');;     next();   }); };  notebookschema.plugin(customidplugin ); 

these 2 approaches work fine, , i'm aware there's no "official magical standardized" ways, can tell me choice , why (pro , cons)


Comments