-
-
Save viczam/3306456d3c63e2c21f1d to your computer and use it in GitHub Desktop.
mongoose localized schema
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'), | |
Schema = mongoose.Schema, | |
_ = require('lodash'); | |
function objectPath(object, path, value) { | |
var subpaths = path.split(/\./), | |
last = object[subpaths[0]] | |
length = (value === undefined) ? subpaths.length: subpaths.length - 1; | |
for (var i = 1; i < length; i++) { | |
last = last[subpaths[i]]; | |
} | |
if (value === undefined) { | |
return last; | |
} else { | |
last[subpaths[i]] = value; | |
} | |
} | |
module.exports = exports = function(schema, options) { | |
if (!options.languages || !_.isArray(options.languages)) { | |
throw 'You must pass an array of languages as an options!'; | |
} | |
schema.eachPath(function(path, config) { | |
if (config.options.i18n) { | |
delete(config.options.i18n); | |
schema.remove(path); | |
var nested = {}; | |
options.languages.forEach(function(language) { | |
nested[language] = config.options; | |
}); | |
schema.path(path, nested); | |
if (options.currentLanguage) { | |
schema.virtual(path + '.i18n').get(function() { | |
return objectPath(this, path + '.' + options.currentLanguage); | |
}); | |
schema.virtual(path + '.i18n').set(function(value) { | |
return objectPath(this, path + '.' + options.currentLanguage, value); | |
}); | |
} | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
Schema.prototype.remove = function(path) { | |
var subpaths = path.split(/\./), | |
last = subpaths.pop(), | |
branch = this.tree; | |
subpaths.forEach(function(sub, i) { | |
if (!branch[sub]) return; | |
branch = branch[sub]; | |
}); | |
delete(branch[last]); | |
delete(this.paths[path]); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'), | |
i18nPlugin = require('./i18n_plugin'); | |
var TestSchema = new Schema({ | |
title: { | |
type: String, | |
i18n: true | |
} | |
}); | |
TestSchema.plugin(i18nPlugin, {languages: ['en', 'ro'], currentLanguage: 'en'}); | |
mongoose.model('Test', TestSchema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment