Created
October 20, 2012 22:51
-
-
Save hetsch/3925111 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
mongoose = require("mongoose") | |
Schema = mongoose.Schema | |
languages = ['de', 'en', 'es'] | |
defaultLanguage = 'de' | |
getLanguage = () -> | |
return 'de' | |
class MultilingualSchema extends Schema | |
multilingualValues: [] | |
constructor: (obj, options) -> | |
#console.log(obj, options) | |
for key, value of obj | |
# check if we have a multilingual property | |
if 'i18n' of value and value['i18n'] is true | |
delete value['i18n'] | |
@multilingualValues.push key | |
struct = {} | |
for lang in languages | |
# make nested language struct | |
struct[lang] = value | |
# we only need to require one value per language - default language | |
if (lang is defaultLanguage) is false and 'required' of value and value['required'] is true | |
delete struct[lang]['required'] | |
# saving the new multilingual structures | |
obj[key] = struct | |
super(obj, options) | |
for key in @multilingualValues | |
# setting virtual methods for shorthand getters and setters | |
v = "#{key}.i18n" | |
@virtual(v).get () -> | |
return @[key][getLanguage()] | |
@virtual(v).set (value) -> | |
return @[key][getLanguage()] = value | |
db = mongoose.createConnection("localhost", "test") | |
schema = new MultilingualSchema( | |
name: | |
i18n: true | |
type: String | |
trim: true | |
required: true | |
) | |
Dummy = db.model("Dummy", schema) | |
d = new Dummy() | |
d.name.de = "sepp" | |
d.name.en = "joseph" | |
d.name.es = "jose" | |
d.save (err) -> | |
if err | |
return console.log(err) | |
d.name.i18n = 'sepp_1' | |
d.save (err) -> | |
if err | |
return console.log err | |
console.log d.name.i18n | |
console.log d.name.en | |
console.log d.name.es |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here's an alternative approach that conforms better with mongoose way of building plugins - https://gist.github.com/viczam/3306456d3c63e2c21f1d