MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Prototipo di Mongoose:come inserire un URL in modo dinamico?

Ecco un esempio che utilizza un metodo di istanza :

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

Se desideri che gli URL facciano parte dell'oggetto del documento (ad esempio, da utilizzare come risposta JSON), utilizza un "virtuali" invece:

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