Home > Back-end >  Store image at MongoDB using Gridfs or BSON
Store image at MongoDB using Gridfs or BSON

Time:03-29

I am new to MongoDB. I would like to store images to the database. I know there is 2 ways that I can do to store the images, one is Gridfs, another one is BSON. What is the pros and cons for these two implementations? The only different that I know is that BSON has a 16MB size limit.

Another thing that I am confused about is how to use either ways to implement the model and the APIs. Any suggestions will be really helpful!!

I have a model called Image, which has id, brief description, and the actual image. Here is the code for my Image model.

const Image = mongoose.model('Image', {
    imageID: {
        type: mongoose.SchemaTypes.ObjectId,
        required: true,
    },
    img: { 
        <What should I put here? >
    },
        description: {
            type: String,
            required: false
        },
})

And I need APIs to handle the uploading image (store the image to the database, get image by ID, delete image by ID).

This is what I have for get by ID

app.get('/api/images/:id', async (req, res) => {
        
        const result = Image.find({imageID: req.body.imageID})

        if (id) {
             res.send({result})
        }
    })

Feel free to point out if there is something wrong in my codes!!

Any explaination and examples would be super helpful! Thank you!

CodePudding user response:

MongoDB isn't made to store images, of course you can (very limited), but it's best to use another solution such as Amazon S3 or Google Cloud storage.

You then take the url from those stored images and store that url as a field in your mongo document. You use it basically as a pointer to the image.

If you do want to use mongoDB then you will need to use multer a good video on that is Uploading an Image | Creating a REST API with Node.js.

Again. I want to reiterate the best approach is to use a 3rd party for storing large files such as images. MongoDB has size limits to their documents.

Also if you're going to store this database remotely using Atlas then those images will take over your database limits VERY quickly. You have a limit of 500MB when using the free cluster, so unless you intend on paying, it's best to use something else.

  • Related