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;
});

Schema.toJSON() should be used in a service, after the records are found.