Question

How to store images in Digital Ocean managed MongoDB database using Prisma client and NodeJs

I have gone through various articles and tutorials and managed to build a Rest Api in NodeJs through which I can upload data to Digital Ocean Managed MongoDB. I am using Prisma client for schema and successfully able to store information like id,name,etc. But,how can I store or upload images in Digital Ocean Managed MongoDB database through my Rest Api in NodeJs while using Prisma client for schema?


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Bobby Iliev
Site Moderator
Site Moderator badge
April 10, 2023

Hi there,

Generally speaking, storing images directly in a database is not really recommended. This is valid for MongoDB as well. Storing your images in your database directly can lead to performance issues and quickly consume your database storage.

Instead, it’s better to store images in an object storage service, such as DigitalOcean Spaces, and save the image URL in your MongoDB database.

You can follow the steps here on how to upload images to the S3 storage here:

https://www.digitalocean.com/community/tutorials/how-to-upload-a-file-to-object-storage-with-node-js

But in general, the process will look as follows:

  1. Set up a DigitalOcean Space:

    First, create a DigitalOcean Space and generate an access key and secret key. You’ll need these to configure your Node.js app to connect to Spaces.

  2. Install dependencies:

    In your Node.js project, install the required dependencies:

    npm install aws-sdk multer multer-s3

    aws-sdk is the AWS SDK for Node.js, which we’ll use to connect to DigitalOcean Spaces. multer is a middleware for handling multipart/form-data (used for file uploads), and multer-s3 is an extension for Multer to upload files directly to AWS S3-compatible services, like DigitalOcean Spaces.

  3. Configure DigitalOcean Spaces:

    Create a new file in your project, e.g., spaces.js, and configure the AWS SDK and Multer to work with DigitalOcean Spaces:

const AWS = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');

const spacesEndpoint = new AWS.Endpoint('nyc3.digitaloceanspaces.com'); // Replace with your Spaces endpoint
const s3 = new AWS.S3({
  endpoint: spacesEndpoint,
  accessKeyId: 'YOUR_ACCESS_KEY',
  secretAccessKey: 'YOUR_SECRET_KEY',
});

const upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'your-space-name',
    acl: 'public-read',
    key: function (req, file, cb) {
      cb(null, Date.now().toString() + '-' + file.originalname);
    },
  }),
});

module.exports = upload;

Replace 'YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY', 'your-space-name', and 'nyc3.digitaloceanspaces.com' with your DigitalOcean Spaces credentials and endpoint.

  1. Update your REST API to handle file uploads:

    In your main Node.js file or your routes file, import the upload middleware and use it in the route that handles image uploads:

const express = require('express');
const app = express();
const upload = require('./spaces'); // Import the upload middleware
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

app.use(express.json());

// Add a new route for image uploads
app.post('/upload', upload.single('image'), async (req, res) => {
  const imageUrl = req.file.location;
  const name = req.body.name;

  try {
    const result = await prisma.yourModel.create({
      data: {
        name: name,
        imageUrl: imageUrl,
      },
    });
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: 'Error uploading image' });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Replace yourModel with the name of the Prisma model you want to use to store the image URL. Make sure your Prisma schema includes a field for storing the image URL, e.g., imageUrl String.

  1. Update your Prisma schema:

    Ensure your Prisma schema has a model with a field for storing the image URL. For example:

model YourModel {
  id        Int      @id @default(autoincrement())
  name      String
  imageUrl  String
  // The rest of your columns
}

Replace YourModel with the name of the model you want to use, and adjust the fields as needed.

  1. Test the image upload:

    You can now test the image upload functionality by sending a POST request to the /upload endpoint, including the image file and any additional data (e.g., name). You can use a tool like Postman, or you can create a simple HTML form to test the upload:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Image Upload</title>
</head>
<body>
  <h1>Upload an image</h1>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br><br>
    <label for="image">Image:</label>
    <input type="file" id="image" name="image" accept="image/*" required><br><br>
    <input type="submit" value="Upload">
  </form>
</body>
</html>

After completing these steps, your REST API should be able to handle image uploads, store the images in DigitalOcean Spaces, and save the image URLs in your DigitalOcean Managed MongoDB database using the Prisma client.

Hope that this helps!

Best,

Bobby

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up