SchemaType.prototype.get()
Parameters
- fn «Function»
Returns:
- «SchemaType» this
Adds a getter to this schematype.
Example:
function dob (val) {
if (!val) return val;
return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
}
// defining within the schema
const s = new Schema({ born: { type: Date, get: dob })
// or by retreiving its SchemaType
const s = new Schema({ born: Date })
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:
function obfuscate (cc) {
return '****-****-****-' + cc.slice(cc.length-4, cc.length);
}
const AccountSchema = new Schema({
creditCardNumber: { type: String, get: obfuscate }
});
const Account = db.model('Account', AccountSchema);
Account.findById(id, function (err, found) {
console.log(found.creditCardNumber); // '****-****-****-1234'
});
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.
function inspector (val, schematype) {
if (schematype.options.required) {
return schematype.path + ' is required';
} else {
return schematype.path + ' is not';
}
}
const VirusSchema = new Schema({
name: { type: String, required: true, get: inspector },
taxonomy: { type: String, get: inspector }
})
const Virus = db.model('Virus', VirusSchema);
Virus.findById(id, function (err, virus) {
console.log(virus.name); // name is required
console.log(virus.taxonomy); // taxonomy is not
})
当前内容版权归 mongoosejs 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 mongoosejs .