append the data in response using mongoose and expressJs

Viewed 26

I am trying to append the image for each user, such that if I do res.send(), it should provide me all the users along their images in base64 format. I am trying to loop each user and appending the data. But that is not working, Can anyone tell me how could I solve this?

router.get("/employee", async (req, res) => {
  const getUsers = await User.find();

  if (!getUsers) {
    res.send({
      message: "No User Found",
    });
  } else {
    // console.log(getUsers.length);
    let bufferDecoded;
    for (var i = 0; i < getUsers.length; i++) {
        const _id = new mongoose.Types.ObjectId(getUsers[i].image.id);
    console.log(_id);
    await gfs.files
      .find({ filename: getUsers[i].image.filename })
      .toArray(async (err, files) => {
        if (!files || files.length === 0) {
          res.send({
            message: "No User Found",
          });
        } else {
          console.log("hello");
          const data = [];
          const readStream = gridfsBucket.openDownloadStream(_id);
          readStream.on("data", (chunk) => {
            data.push(chunk);
          });
          readStream.on("error", async (error) => {
            res.send(error);
          });
          readStream.on("end", async (err) => {
            let bufferBase64 = Buffer.concat(data);
            bufferDecoded =
              "data:image/png;base64," + bufferBase64.toString("base64");
              
            getUsers[0].image = bufferDecoded;
            
          });
         
        }
      });
    }
    res.send({
        message: "Data Fetched",
        data: getUsers
        
      });
    
  }
});

I am getting the fata from mongo GridFS stream.

The resopnse which I am getting enter image description here

Whereas the expected response should be that for image attribute it should show the base64 encoded strieng for each user present in that database.

0 Answers
Related