0

Regarding these post : Mongoose prototype : how to insert an url dynamically?

I'm looking to do pretty much the same (URI dynamically insert). The solution provided is good but I do not understand some things...

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

PicturesSchema.virtual('pictureUrls').get(function() {
  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() );
  1. The given solution injects a "virtual field" in addition to retaining the "pictures" field with the name of the images (without URL).

How to retain only the field "PicturesURL" containing the full URL of the image without displaying a redundancy with the "Pictures" field?

  1. How to retrieve and display the JSON format query results as it knowing that data.ToJson returns an error: has no method 'toJson'?

    Pictures.find().exec(function(err, data){

        if(err){
            console.log(err);
        }
    
        console.log('%j', data.toJSON({ virtuals : true }) );
    });
    

1 Answer 1

0

A strategy to store only the picture url without the picture would be to create a Mongoose middleware on save.

You could then populate the picture field with the name of the picture, and the full url will be the one stored in the database and later retrieved.

For example:

PictureSchema.pre('save', function (next){
  if (this.isModified(pictureUrls){
    this.pictureUrls = this.pictureUrls.map(function(picture){
      return 'https://s3.amazonaws.com/xxxxx/'+ picture;
    })
  }
});

With this solution, every time you modify the pictures array, it will go over every element of the array and add the s3 path.

Since it won't be a virtual, it will be easier for you to use the model with event using toObject or toJson.

Sign up to request clarification or add additional context in comments.

Comments

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.