Skip to content

Instantly share code, notes, and snippets.

@hetsch
Created October 20, 2012 22:51
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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
@RBLU
Copy link

RBLU commented Jan 31, 2014

Hello @hetsch, I stumbled over this gist in google looking for ideas how to implement localized fields in mongoose. Have you eventually used this approach here?
If yes, how do you handling the getLanguage() in a real app when the user's locale is coming from the request?
thanks
Reto

@viczam
Copy link

viczam commented Mar 20, 2014

here's an alternative approach that conforms better with mongoose way of building plugins - https://gist.github.com/viczam/3306456d3c63e2c21f1d

@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