如何将产品表单和图像上传到MongoDB Atlas服务器?

问题描述

我建立了一个电子商务网站,并使用提取功能将产品数据提取到后端。像这样

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)
};






});

然后我像这样使用GridFS和Multer将此表单中的图像上传到我的MongoDB服务器

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;

问题是当我使用这样的发帖请求

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

照片不保存到我的数据库中,只有controllpages.hostPost中的产品信息保存。

当我将发布请求与其他任何其他功能一起使用时

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

照片确实保存到我的数据库中,但我丢失了产品信息。

我该怎么办?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)