'MERN Stack and cloudinary file upload

I've been searching everywhere still couldn't find a solution regarding this matter. I've build a small ReactJS app integrated with Express, Mongoose and Cloudinary library. The issue I'm having is I can't find a way to validate db issues such as incorrect schema values, db disconnected before sending the CRUD requests. So if the examples mentioned above occur, the app still uploads the files to cloudinary regardless the db status. So what i'm looking for is to get the server to ping/check status of the db before uploading the file.

db.js

const mongoose = require("mongoose");
const { Schema, model, connect } = mongoose;
const localDB = "mongodb://localhost:27017/cloudinaryDemo";
const remoteDB = process.env.REMOTE_DB;
function dbConnect() {
  try {
    connect(remoteDB || localDB, () => console.log("DB CONNECTED"));
  } catch (error) {
    throw error;
  }
}

const ImageSchema = new Schema({
  images: Array,
});
const ImageModel = model("Image", ImageSchema);

module.exports = { dbConnect, ImageModel };

server.js

const express = require("express");
const app = express();
const path = require("path");
const dotenv = require("dotenv").config();
const port = process.env.PORT || 5000;
const { cloudinary } = require("./utils/cloudinary");
const { dbConnect, ImageModel } = require("./config/db");
dbConnect();

app.use(express.urlencoded({ extended: true }));
app.use(express.json({ limit: "50mb" }));

app.use(express.static(path.resolve(__dirname, "./frontend/build")));

app.get("/api/images", async (req, res) => {
  try {
    const images = await ImageModel.find().sort({ _id: -1 });
    res.json(images);
  } catch (error) {
    console.error(error);
  }
});

app.delete("/api/images", async (req, res) => {
  try {
    const image = await ImageModel.findById(req.body.data);
    const pubId = image.images[0].public_id;
    const deleteResponse = await cloudinary.uploader.destroy(pubId);
    if (deleteResponse) {
      await ImageModel.findByIdAndDelete(req.body.data);
    }
    console.log("deleted");
    res.json(image);
  } catch (error) {
    console.error(error);
  }
});

app.post("/api/upload", async (req, res) => {
  try {
    const fileStr = req.body.data;
    const uploadedResponse = await cloudinary.uploader.upload(fileStr, {
      upload_preset: "dev_setups",
    });
    if (uploadedResponse) {
      const image = await ImageModel.create({ images: uploadedResponse });
      image.save();
    }

    res.json({ message: "YAAAAY" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "OH DUKES!" });
  }
});

app.listen(port, () => console.log(`Backend Loaded on port ${port}`));


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source