Home > Net >  Can i implement get in ref
Can i implement get in ref

Time:10-20

I have images stored in buffer and referred in news. When I populate images, I need them to be as Base64 URL. Is it doable

const mongoose = require('mongoose')

const Schema = mongoose.Schema({
  title: String,
  description: String,
  images: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'File',
    get: (image) => {
      return { 
        title: image.title,
        url: `data:${image.mimeType};base64,${Buffer.from(image.data.data).toString('Base64')}`
      }
    }
  }],
  content: String,
  status: String,
  date: {
    type: Date,
    default: () => new Date()
  }
}, { 
  collection: 'news' 
})

module.exports = mongoose.models.News || mongoose.model('News', Schema)

CodePudding user response:

Not in the schema declaration. Each schema maps to a MongoDB collection and defines the shape of the documents you should look up about valid types here (See more about SchemaTypes here)

I can think of two solutions. First would be to save in File your images not as Buffer but as base64.

Second solution would be to convert your images after population with a map function.

  • Related