@@ -10,7 +10,7 @@ block content
10
10
SchemaTypes handle definition of path
11
11
[defaults](./api.html#schematype_SchemaType-default),
12
12
[validation](./api.html#schematype_SchemaType-validate),
13
- [getters](./api.html#schematype_SchemaType-get ),
13
+ [getters](#getters ),
14
14
[setters](./api.html#schematype_SchemaType-set),
15
15
[field selection defaults](./api.html#schematype_SchemaType-select) for
16
16
[queries](./api.html#query-js),
@@ -375,6 +375,68 @@ block content
375
375
Keys in a BSON object are ordered, so this means the [insertion order](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description)
376
376
property of maps is maintained.
377
377
378
+ <h3 id="getters"><a href="#getters">Getters</a></h3>
379
+
380
+ Getters are like virtuals for paths defined in your schema. For example,
381
+ let's say you wanted to store user profile pictures as relative paths and
382
+ then add the hostname in your application. Below is how you would structure
383
+ your `userSchema`:
384
+
385
+ ```javascript
386
+ const root = 'https://s3.amazonaws.com/mybucket';
387
+
388
+ const userSchema = new Schema({
389
+ name: String,
390
+ picture: {
391
+ type: String,
392
+ get: v => `${root}${v}`
393
+ }
394
+ });
395
+
396
+ const User = mongoose.model('User', userSchema);
397
+
398
+ const doc = new User({ name: 'Val', picture: '/123.png' });
399
+ doc.picture; // 'https://s3.amazonaws.com/mybucket/123.png'
400
+ doc.toObject({ getters: false }).picture; // '123.png'
401
+ ```
402
+
403
+ Generally, you only use getters on primitive paths as opposed to arrays
404
+ or subdocuments. Because getters override what accessing a Mongoose path returns,
405
+ declaring a getter on an object may remove Mongoose change tracking for
406
+ that path.
407
+
408
+ ```javascript
409
+ const schema = new Schema({
410
+ arr: [{ url: String }]
411
+ });
412
+
413
+ const root = 'https://s3.amazonaws.com/mybucket';
414
+
415
+ // Bad, don't do this!
416
+ schema.path('arr').get(v => {
417
+ return v.map(el => Object.assign(el, { url: root + el.url }));
418
+ });
419
+
420
+ // Later
421
+ doc.arr.push({ key: String });
422
+ doc.arr[0]; // 'undefined' because every `doc.arr` creates a new array!
423
+ ```
424
+
425
+ Instead of declaring a getter on the array as shown above, you should
426
+ declare a getter on the `url` string as shown below. If you need to declare
427
+ a getter on a nested document or array, be very careful!
428
+
429
+ ```javascript
430
+ const schema = new Schema({
431
+ arr: [{ url: String }]
432
+ });
433
+
434
+ const root = 'https://s3.amazonaws.com/mybucket';
435
+
436
+ // Good, do this instead of declaring a getter on `arr`
437
+ schema.path('arr.0.url').get(v => `${root}${v}`);
438
+ ```
439
+
378
440
<h3 id="customtypes"><a href="#customtypes">Creating Custom Types</a></h3>
379
441
380
442
Mongoose can also be extended with custom SchemaTypes. Search the
0 commit comments