0

Whilst working on a project of mine, I experienced a small predicament where I needed to save images to my mongoDB database and output them via my Rest API. I did not find much helpful documentation on the topic and it took me a few days to figure out the solution.

For people in the same situation as me I have the answers.

Step 1

Firstly we need to fetch the image from our uri. We will use the request npm package and set encoding to null by default. This is important as it will respond with our data in binary form

var request = require("request").defaults({ encoding: null });
...

function fetchImage(imageUri) {
  return new Promise((resolve, reject) => {
    request.get(imageUri, function (err, res, body) {
      if (err) {
        reject(err);
      } else {
        resolve(body);
      }
    });
  });
}

Step 2

Now the we have our data in binary form we can store it in our MongoDB document. The best practice to storing images in MongoDB is by saving it in Binary form.

fetchImage(URI)
      .then((binaryString) => {

        const image = new imageModel({
          image: binaryString,
        });

        image
          .save()
          .then((result) => {
            console.log(result);
            resolve("done");
          })
      }) 
      .catch((err) => reject(err));

Step 3

Now that our image is stored as binary in our database, we can easily retrieve and display it with our REST api.

function searchMongoImage(searchKey) {
  return new Promise((resolve, reject) => {
    imageModel
      .findOne({ primaryKey: searchKey })
      .then((doc) => {
        if (doc != null) {
          resolve(doc); // item is in db
        } else {
          reject("Item not in db"); 
        }
      })
      .catch((err) => alert(err));
  });
}

router.get("/images/search/:searchKey", function (req, res, next) {
  searchMongoImage(req.params.searchKey)
    .then((doc) => {
      res.status(200).type("png").send(doc.image);
    })
    .catch((err) => {
      console.log(err);
     //error handling and respond with a 404 page here
    });
});

The API will now output our binary in the browser and display it in a PNG format.

I hope that this will help someone who has encountered a similar situation and save them some time digging through unrelated forum posts :)

If anyone has questions or would like some help understanding the code feel free to ask me!

  • 1
    you can write your answer to related questions. you hve posted it as a question and this is not the right place – Heartbit Dec 25 '21 at 22:26
  • Does this answer your question? [Which is the best way to store images for expressjs, mongodb site?](https://stackoverflow.com/questions/55963408/which-is-the-best-way-to-store-images-for-expressjs-mongodb-site) – Heartbit Dec 25 '21 at 22:30

0 Answers0