Search code examples
node.jsmongoosemultermulter-s3

How to link S3 URL to MongoDB in Node.js?


I have an empty mind on how to link a specific movie URL to mongoose model. I'm using multer-s3 and multer for form/multi-part body to upload a specific file, and I literally have no idea how to get the URL from multer to put it into the database.

import { Router } from 'express'
import { MovieController } from 'movies/controller'
import { SPACES_BUCKET, SPACES_ENDPOINT, SPACES_PRIVATE, SPACES_PUBLIC } from 'utils/envfile'

import multer from 'multer'
import multerS3 from 'multer-s3'
import aws from 'aws-sdk'

aws.config.update({
    accessKeyId: SPACES_PUBLIC,
    secretAccessKey: SPACES_PRIVATE,
})

const s3 = new aws.S3({
    endpoint: SPACES_ENDPOINT,
})

const upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: SPACES_BUCKET,
        acl: 'public-read',
        key: function (request, file, cb) {
            console.log(file)
            cb(null, file.originalname)
        },
    }),
})

export class MovieRouter {
    public router: Router
    public controller: MovieController = new MovieController()

    constructor() {
        this.router = Router()
        this.routes()
    }

    public routes() {
        this.router.get('/', this.controller.getMovies)
        this.router.post('/', upload.single('movie'), this.controller.createMovie)
    }
}

I think the controller code doesn't matter here because my problem is about referencing data provided at cb(null, file.originalname). Does somebody have idea how to reference it?


Solution

  • After uploading to the S3 bucket, should be returned the data, where you can find a "Location". It will be your file URL.

    Or you can create a URL manually on your side.

    const url = `${BUCKET_URL}/${YOUR_KEY_FROM_UPLOAD_FUNCTION}`;
    

    "YOUR_KEY_FROM_UPLOAD_FUNCTION" can also include the album name.

    Examples:

    YOUR_KEY_FROM_UPLOAD_FUNCTION : /users/ee44e698-73cd-4fe8-99e0-f82dd4ac221b.png BUCKET_URL: https://s3.amazonaws.com/YOUR_BUCKET_NAME