Skip to content

Instantly share code, notes, and snippets.

@viczam
Last active August 29, 2015 13:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viczam/3306456d3c63e2c21f1d to your computer and use it in GitHub Desktop.
Save viczam/3306456d3c63e2c21f1d to your computer and use it in GitHub Desktop.
mongoose localized schema
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);
});
}
}
});
}
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]);
}
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