Getter and setter in mongodb

0 Shares
0
0
0
0

Introduction

getand setThey help you change how properties defined by keys and values in the underlying raw document are retrieved and set.

setters

set They allow you to transform mongoose document data before it reaches the raw MongoDB document and is set as a value to an actual key.

Let's say you're implementing user registration for a website. Users provide an email and password, which are stored in MongoDB. Email is a string that you want to normalize to lowercase so that one email doesn't have more than one account. For example, [email protected] can be registered for two accounts via [email protected] and [email protected].

You can easily configure email case normalization via Mongoose's setter. Notice in the following snippet that the setters (as well as the recipients) are defined in the Schema:

function toLower (v) {
return v.toLowerCase();
}
var UserSchema = new Schema({
email: { type: String, set: toLower } 
});
var User = mongoose.model('User', UserSchema);
var user = new User({email: '[email protected]'});
console.log(user.email); // '[email protected]'

As you can see above, setters allow you to transform data before it reaches the raw mongodb document and set it as a value to an actual key.

getters

get They allow you to transform data views as you navigate from the raw MongoDB document to what you see.

Let's say you're storing a credit card number and you want to hide everything except the last 4 digits from the Mongoose user. You can do this by defining a recipient like this (note again that recipients are defined in the Schema):

function obfuscate (cc) {
return '****-****-****-' + cc.slice(cc.length-4, cc.length);
}
var AccountSchema = new Schema({
creditCardNumber: { type: String, get: obfuscate }
});
var Account = mongoose.model('Account', AccountSchema);
Account.findById( someId, function (err, found) {
console.log(found.creditCardNumber); // '****-****-****-1234'
});

Result

Setters are intended to modify the underlying raw data. Getters are intended to transform (but not modify at the raw data level) the underlying raw data into what the user expects to see. Both are defined in the Schema definition.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like