diff --git a/docs/tutorials/getters-setters.md b/docs/tutorials/getters-setters.md index dc94fb6a41b..48aebce9182 100644 --- a/docs/tutorials/getters-setters.md +++ b/docs/tutorials/getters-setters.md @@ -70,6 +70,19 @@ below. [require:getters/setters.*setters.*update skip] ``` +## Passing Parameters using `$locals` + +You can't pass parameters to your getter and setter functions like you do to normal function calls. +To configure or pass additional properties to your getters and setters, you can use the document's `$locals` property. + +The `$locals` property is the preferred place to store any program-defined data on your document without conflicting with schema-defined properties. +In your getter and setter functions, `this` is the document being accessed, so you set properties on `$locals` and then access those properties in your getters examples. +For example, the following shows how you can use `$locals` to configure the language for a custom getter that returns a string in different languages. + +```javascript +[require:getters/setters.*localization.*locale] +``` + Differences vs ES6 Getters/Setters ---------------------------------- diff --git a/test/docs/getters-setters.test.js b/test/docs/getters-setters.test.js index 80c7d1799a9..1c5c89bb610 100644 --- a/test/docs/getters-setters.test.js +++ b/test/docs/getters-setters.test.js @@ -174,4 +174,53 @@ describe('getters/setters', function() { // acquit:ignore:end }); }); + describe('localization', function() { + it('locale', async function() { + const internationalizedStringSchema = new Schema({ + en: String, + es: String + }); + + const ingredientSchema = new Schema({ + // Instead of setting `name` to just a string, set `name` to a map + // of language codes to strings. + name: { + type: internationalizedStringSchema, + // When you access `name`, pull the document's locale + get: function(value) { + return value[this.$locals.language || 'en']; + } + } + }); + + const recipeSchema = new Schema({ + ingredients: [{ type: mongoose.ObjectId, ref: 'Ingredient' }] + }); + + const Ingredient = mongoose.model('Ingredient', ingredientSchema); + const Recipe = mongoose.model('Recipe', recipeSchema); + + // Create some sample data + const { _id } = await Ingredient.create({ + name: { + en: 'Eggs', + es: 'Huevos' + } + }); + await Recipe.create({ ingredients: [_id] }); + + // Populate with setting `$locals.language` for internationalization + const language = 'es'; + const recipes = await Recipe.find().populate({ + path: 'ingredients', + transform: function(doc) { + doc.$locals.language = language; + return doc; + } + }); + + // Gets the ingredient's name in Spanish `name.es` + assert.equal(recipes[0].ingredients[0].name, 'Huevos'); // 'Huevos' + }); + }) }); \ No newline at end of file