I am getting array of objects which contain base 64 images . I have to convert base64 images into url and have to save in db. But the problem i i have a loop which contain a single image and convert string to url. But i am getting issue of await . Because the file is still writing string to url but loop move to other file so i am not able to propely save the all files. Here is my code
let attachments =[]
for (let i = 0; i < files.length; i++) {
//Get Base64
if (
files[i].base64 &&
files[i].base64 != null &&
files[i].base64 != ""
) {
let base64 = files[i].base64.split(";base64,").pop();
let path = `uploads/${Date.now()}-${files[i].name}`;
fs.writeFile(
`${path}`,
base64,
{
encoding: "base64",
},
async function (err) {
if (err) {
console.log(err);
return res.status(400).send(err.message);
} else {
attachments.push({
attachmentTitle: files[i].attachmentTitle,
eAttachmentT: files[i].attachmentTitle,
eAttachmentPath: path,
eAttachmentURL: path,
description: files[i].description,
});
await Model.findOneAndUpdate(
{
"level1.email": req.body.email,
},
{
$set: {
"level2.attachments": attachments,
},
}
).then(async (respo) => {
// console.log("up");
// console.log(attachments);
if (files.length === i + 1) {
if (Model.level1.supplierStatus == "REJECTED") {
await axios({
method: "post",
url: `${process.env.SELF}/rgt`,
data: {
vendorId: respo._id,
},
})
.then((resp) => {
return res.status(200).send(resp.data);
})
.catch((err) => {
return res.status(400).send(err);
});
} else {
let result = await Model.findOne({
"level1.email": req.body.email,
});
return res
.status(200)
.send(result.level2.attachments);
}
}
});
}
}
);
}