0

How can I store an image into MongoDB using the below scenario.

  • Below is my product schema, I want to add another field image into it and manually post the image along with the other fields using Product.create or Product.insertMany method (example below).
  • Inserting image manually means I have grabbed some product images from Google but I am unable to figure out how to store them in MongoDB and use them in my front end.
  • My goal is just to display all the products using the frontend React app along with the image and its details.
const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
  name: String,
  category: String,
  price: Number,
});

const Product = mongoose.model('Product', productSchema);

module.exports = Product;
// Product.insertMany(
//   [
//     { name: 'Shoe one', category: 'Shoes', price: 3599 },
//     { name: 'Shirt one', category: 'Upperwear', price: 380 },
//   ],
//   (err) => {
//     if (err) console.log('error');
//   }
// );
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 3
    Does this answer your question? [Store images in a MongoDB database](https://stackoverflow.com/questions/4796914/store-images-in-a-mongodb-database) – David Oganov Sep 28 '21 at 10:39

1 Answers1

1

Store your image as an array by using type Buffer as follows

const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
    name: String,
    category: String,
    price: Number,
    img:
    {
        data: Buffer,
        contentType: String
    }

});

const Product = mongoose.model('Product', productSchema);

module.exports = Product;
Ezani
  • 535
  • 3
  • 18
  • Okay, but then how will i manually post an image to db using post.create ? Means how what value should i put for the img.data key -- `{ name: 'Shirt one', category: 'Upperwear', price: 380, img: {data : ?????} }` – Satyam Gupta Sep 28 '21 at 10:37
  • @SatyamGupta, check this URL out : https://stackoverflow.com/questions/34485420/how-do-you-put-an-image-file-in-a-json-object Basically you need to convert your image to Base64 encoding and then convert it back later at server end. Read the URL above. – Ezani Oct 01 '21 at 04:19