SchemaType.prototype.get()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Adds a getter to this schematype.

Example:

  1. function dob (val) {
  2. if (!val) return val;
  3. return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
  4. }
  5. // defining within the schema
  6. const s = new Schema({ born: { type: Date, get: dob })
  7. // or by retreiving its SchemaType
  8. const s = new Schema({ born: Date })
  9. s.path('born').get(dob)

Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.

Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:

  1. function obfuscate (cc) {
  2. return '****-****-****-' + cc.slice(cc.length-4, cc.length);
  3. }
  4. const AccountSchema = new Schema({
  5. creditCardNumber: { type: String, get: obfuscate }
  6. });
  7. const Account = db.model('Account', AccountSchema);
  8. Account.findById(id, function (err, found) {
  9. console.log(found.creditCardNumber); // '****-****-****-1234'
  10. });

Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.

  1. function inspector (val, schematype) {
  2. if (schematype.options.required) {
  3. return schematype.path + ' is required';
  4. } else {
  5. return schematype.path + ' is not';
  6. }
  7. }
  8. const VirusSchema = new Schema({
  9. name: { type: String, required: true, get: inspector },
  10. taxonomy: { type: String, get: inspector }
  11. })
  12. const Virus = db.model('Virus', VirusSchema);
  13. Virus.findById(id, function (err, virus) {
  14. console.log(virus.name); // name is required
  15. console.log(virus.taxonomy); // taxonomy is not
  16. })