Mongoose notes

Custom getters

Use custom getters to process the MongoDB retunred data, like an interceptor.

Schema custom getters doesn’t work with lean().

Set up the Schema:

1
2
DBSchema.set('toObject', {getters: true, virtuals: true});
DBSchema.set('toJSON', {getters: true, virtuals: true});

Add custom get function on specified field:

1
2
3
4
5
6
7
8
DBSchema.path('images').get(function (images) {
if (images && Array.isArray(images) && images.length > 0) {
images = images.map(function (image) {
return getUrl(image);
});
}
return images;
});

Read More

JavaScript OO

ONE script to understand JavaScript OO :-)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function MyClass () { // constructor function
var privateVariable = "foo"; // Private variable

this.publicVariable = "bar"; // Public variable

this.privilegedMethod = function () { // Public Method
alert(privateVariable);
};
}

// Instance method will be available to all instance but only load once in memory
MyClass.prototype.publicMethod = function () {
alert(this.publicVariable);
};

// Static variable shared by all instance
MyClass.staticProperty = "baz";

//...
var myInstance = new MyClass();

Clipped from StackOverflow: http://stackoverflow.com/a/1535687/1904043