I have a field which contain url to an image which is protected. It needs a secret to access file and the secret expire after a time. I want that when I do Mode.find()
then the url value get replaced by anther url which contains the secret. So, that I don’t have to manually every where I find from the model.
const schema = new Schema({ url:String }) const Model = model('ModelName', Schema)
- Saved url in database
url:"id_of_image.jpg"
- Expected url when find
url:"/uploads/id_of_image.jpg?secret=xxxxxxxxxxxxxxxxx"
Advertisement
Answer
In this case, you can use virtuals. Something like:
const schema = new Schema({ url:String }, { // use these options to include virtual fields in response toJSON: { virtuals: true }, toObject: { virtuals: true } }); schema.virtual('secretUrl').get(function() { return this.url + ' ' + yourSecret; });
Or if you want to replace your url
field with secret url, you can use getters.