Her er et eksempel, der bruger en instansmetode :
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() );
Hvis du ønsker, at URL'erne skal være en del af dokumentobjektet (for eksempel til brug som JSON-svar), skal du bruge en "virtuel" i stedet:
...
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 }) );