Skip to content

Instantly share code, notes, and snippets.

@hetsch
Created October 20, 2012 22:51
Show Gist options
  • Save hetsch/3925111 to your computer and use it in GitHub Desktop.
Save hetsch/3925111 to your computer and use it in GitHub Desktop.
mongoose localized schema
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
@hyzhak
Copy link

hyzhak commented Oct 20, 2014

Same question as @RBLU has. and @viczam alternative solution doesn't solve this issue.

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