Berikut adalah contoh menggunakan metode instan :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PicturesSchema = new Schema({
album : { type : String, required : true, trim : true },
pictures : { type : Array, required : false, trim : true }
});
// Make sure this is declared before declaring the model itself.
PicturesSchema.methods.getPics = function() {
// `this` is the document; because `this.pictures` is an array,
// we use Array.prototype.map() to map each picture to an URL.
return this.pictures.map(function(picture) {
return 'https://s3.amazonaws.com/xxxxx/'+ picture;
});
};
var Pictures = mongoose.model('Pictures', PicturesSchema);
// Demo:
var pictures = new Pictures({
album : 'album1',
pictures : [
'1434536659272.jpg',
'1434536656464.jpg',
'1434535467767.jpg'
]
});
console.log( pictures.getPics() );
Jika Anda ingin URL menjadi bagian dari objek dokumen (misalnya, untuk digunakan sebagai respons JSON), gunakan "virtual" sebagai gantinya:
...
PicturesSchema.virtual('pictureUrls').get(function() {
return this.pictures.map(function(picture) {
return 'https://s3.amazonaws.com/xxxxx/'+ picture;
});
});
...
// Demo:
console.log('%j', pictures.toJSON({ virtuals : true }) );