how to upload products form and images to MongoDB atlas server?

375 views Asked by At

I build a e-commerce website and i use fetch function to fetch the product data to the back end. like so

const form = document.querySelector('form');


form.addEventListener('submit', async(e) => {

e.preventDefault();

// get data from infront end

const title = form.title.value;
const category = form.category.value;
const hostKind = form.hostingKind.value;
const area = form.area.value;
const realStateDesc = form.realstateDisc.value;
const neighbourhoodDesc = form.neighbourhood.value;
const governorate = form.governorate.value;
const city = form.city.value;
const address = form.address.value;
const zipCode = form.zipCode.value;
const peopleAllowed = form.allowed.value;
const peopleMaxNum = form.maxnum.value;
const timeper = form.timeper.value;
const additional = form.additional.value;
const price = form.rentprice.value;
const photos = form.photos.value;

fetch(photos).then(response => {
    console.log(response);
    return response.blob();
})



//fetch data
try {

    const res = await fetch('/host', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({

            title: title,
            category: category,
            hostKind: hostKind,
            area: area,
            realStateDesc: realStateDesc,
            neighbourhoodDesc: neighbourhoodDesc,
            governorate: governorate,
            city: city,
            address: address,
            zipCode: zipCode,
            peopleAllowed: peopleAllowed,
            peopleMaxNum: peopleMaxNum,
            timeper: timeper,
            additional: additional,
            price: price

        })
    });

    //location.assign('/congrats');


} catch (err) {
    console.log(err)
};






});

then i use GridFS and Multer to upload images inside this form to my MongoDB server like so

mongoose.connect(process.env.DB_CONNECT, { useNewUrlParser: true, useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true, })
.then((result) => app.listen(3000))
.catch((err) => console.log(err));
const conn = mongoose.connection;


//init gfs
let gfs;

//const storage = new GridFSStorage({ db: conn });

conn.once('open', () => {
    gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection('uploads');
});

//create storage engine

const storage = new GridFsStorage({
    options: { useUnifiedTopology: true },
    url: process.env.DB_CONNECT,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
                if (err) {
                    return reject(err);
                }

                const filename = buf.toString('hex') + path.extname(file.originalname);
                const fileInfo = {
                    filename: filename,
                    bucketName: 'uploads',

                };
                resolve(fileInfo);
            });
        });
    }
});




const upload = multer({ storage });
module.exports = upload;

the problem is that when i use my post request like that

router.post('/host', upload.single('photos'), controllpages.hostPost);

the photos don't save into my data base ,only the product info from controllpages.hostPost does.

and when i use the post request with any other function like so

router.post('/host', upload.single('photos'), (req , res) => {
  console.log('Done')
};

the photos do save into my database but i lose the product info .

What should i do?

0

There are 0 answers