Mongoose: How to add APP_URL to imageURL when retrieving single image data?

Viewed 105

In ImageSchema, I have some fields - title, imageURL. When I retrieving single image data, I want to add http://localhost:4000/ to imageURL.

"imageURL": "http://localhost:4000/uploads/photo-1508919801845.jpeg",

Example data:

{
    "_id": "612e0328c1c6dd25c6f14fd4",
    "title": "photo-1508919801845",
    "imageURL": "/uploads/photo-1508919801845.jpeg",
    "createdAt": "2021-08-31T10:23:36.419Z",
    "updatedAt": "2021-08-31T10:23:36.419Z",
    "__v": 0
}

Controller.ts

const imageId = req.params.id
const findImage = await Image.findOne({ _id: imageId})
if (!findImage) {
  return res.status(404).json({error: true, msg: "Image not found"})
}
const image = await Image.findById({_id: imageId}).select({ _id: 0, __v: 0})
return res.status(200).json({ error: false, data: image })

How can I do that?

1 Answers

You can use Aggregation pipeline with $concat operator:

Image.aggregate([
  {
    "$match": {
      "_id": "612e0328c1c6dd25c6f14fd4"
    }
  },
  {
    "$set": {
      "imageURL": {
        "$concat": [
          "http://localhost:4000",
          "$imageURL"
        ]
      }
    }
  }
])

Working example

Related