2

I try to create a prototype for a mongoose schema. The database contains a row with a list of pictures.

Example :

{
  "_id": ObjectId("55814a9799677ba44e7826d1"),
  "album": "album1",
  "pictures": [
    "1434536659272.jpg",
    "1434536656464.jpg",
    "1434535467767.jpg"
  ],
  "__v": 0
}

It will be awesome to know how i can inject an URL for each pictures with for example a prototype and how after i can get all the datas from the collection (with pictures and url) in JSOn format (for an API).

I tested many different approach but it doesn't work.

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

var Pictures = mongoose.model('Pictures', PicturesSchema);

// Not working
Pictures.prototype.getPics = function(){
    return 'https://s3.amazonaws.com/xxxxx/'+ this.pictures;
}

module.exports = Pictures;

How I can inject "virtually" the URL for each pictures (I don't want to store the url in the DB) ?

1 Answer 1

3

Here's an example using an instance method:

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

If you want the URL's to be part of the document object (for instance, to use as JSON response), use a "virtual" instead:

...
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 }) );
Sign up to request clarification or add additional context in comments.

1 Comment

work fine but now, how i can get all the data with picture URL, album Name, album ID, ... ? Pictures.find().exec(function(err, data){ if(err){ console.log(err); } return res.json(data); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.