Skip to content

Instantly share code, notes, and snippets.

@wentout
Last active February 6, 2018 21:52
Show Gist options
  • Save wentout/2171022fe597e5b2564435d6b44eac49 to your computer and use it in GitHub Desktop.
Save wentout/2171022fe597e5b2564435d6b44eac49 to your computer and use it in GitHub Desktop.
Attempt to change Mongoose.js Discriminator Value tied mapping leaving Discriminator Name untouched
// https://github.com/Automattic/mongoose/issues/2596
// 1. It was necessary for me to to fit our naming style to this behaviour.
// 2. And moreover, move to Mongoose 5
// 3. And leave all data untouched, I mean, no changes, at all, a lot of production running data.
/**
* Discriminator Reflected mapping
* to discriminator value,
* used inside of existent db
* @param {object} baseModel : parent model used for discriminator creation
* @param {object} discriminatorSchema : shema to create discriminator from
* @param {string} value {string} : your existent Discriminator Key value!
* may be your former discriminator name
* at least 4 me it was so
*/
const createReflectedDiscriminator = (baseModel, discriminatorSchema, value) => {
const parentModelName = baseModel.modelName || baseModel.name;
const discriminatorModelName = `${parentModelName}.${value}`;
const d = baseModel.discriminator(discriminatorModelName, discriminatorSchema);
d.schema.discriminatorMapping.value = value;
baseModel.discriminators[value] = d;
const schema = baseModel.discriminators[value].schema;
const key = schema.options.discriminatorKey;
schema.remove(key);
var obj = {};
obj[key] = {
default : value,
select : true,
set : function(newName) {
if (newName === value) {
return value;
}
throw new Error('Can\'t set discriminator key "' + key + '"');
},
$skipDiscriminatorCheck : true
};
obj[key][schema.options.typeKey] = String;
schema.add(obj);
return d;
};
module.exports = createReflectedDiscriminator;
@wentout
Copy link
Author

wentout commented Feb 6, 2018

It is all about the topic from there
Discriminator Key is tied to Model Name #2596

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