Bug - discriminator and custom _id attribute with unique: true #4881

simonfan opened this Issue Jan 8, 2017 · 3 comments


None yet

3 participants

simonfan commented Jan 8, 2017

When using a custom _id attribute and indexing it as unique in the base schema, attempting to use discriminators fail.

The code (standalone script):

var mongoose = require('mongoose');
var uuid     = require('uuid');


var options = {discriminatorKey: 'kind'};

var eventSchema = new mongoose.Schema({
  _id: {
    type: String,
    default: uuid.v4,
    unique: true,
  time: Date
}, options);
var Event = mongoose.model('Event', eventSchema);

// ClickedLinkEvent is a special type of Event that has
// a URL.
var ClickedLinkEvent = Event.discriminator('ClickedLink',
  new mongoose.Schema({url: String}, options));

The error

      if (typeof to[key] === 'undefined') {

TypeError: Cannot read property 'background' of null
    at merge (/mongoose-discriminator-bug/node_modules/mongoose/lib/utils.js:404:20)
    at merge (/mongoose-discriminator-bug/node_modules/mongoose/lib/utils.js:407:9)
    at merge (/mongoose-discriminator-bug/node_modules/mongoose/lib/utils.js:407:9)
    at Object.merge (/mongoose-discriminator-bug/node_modules/mongoose/lib/utils.js:407:9)
    at merge (/mongoose-discriminator-bug/node_modules/mongoose/lib/model.js:814:11)
    at Function.discriminator (/mongoose-discriminator-bug/node_modules/mongoose/lib/model.js:867:3)
    at Object.<anonymous> (/mongoose-discriminator-bug/index.js:20:30)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:457:10)
    at startup (node.js:136:18)
    at node.js:972:3

Node v5.0.0
Mongodb v3.2.6
mongoose v4.7.6


Thanks for the script @simonfan, I get this error too, so looks like this is def a bug.

@vkarpov15 vkarpov15 added this to the 4.7.7 milestone Jan 11, 2017
@vkarpov15 vkarpov15 closed this in 4efecd5 Jan 13, 2017
vkarpov15 commented Jan 13, 2017 edited

Fixed in master.

More importantly, do not use unique: true on _id or set any indexes on _id. MongoDB puts a special unique index on _id by default, so if you try to set an index on _id your index build will fail.


@vkarpov15 Ohh did not know that, thank you very much for the advice! And for the fix as well :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment