0

I'm having a bit trouble on understanding how can I import csv into my database. I can already export it since DataGrid has the feature to do it, but struggling on importing it back as a backup/restore.

So this is my ProductSchema.js

import mongoose from 'mongoose'

const ProductSchema = new mongoose.Schema({
    seller_id: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
    title: {type: String, required: true},
    description: {type: String, required: true },
    img: {type: String, required:true},
    status: {
        type: String, default: 'available',
    },
    category: {type: String, required: true},
    productCategory: {type: String, required: true},
    price: {type: String, required:true},
    quantity: {type: Number, default: 0}

}, {timestamps: true}
)

export default mongoose.model('Product', ProductSchema)

product.js

 router.post('/addcsv', async (req,res) =>{
    csv()
      .fromFile(req.file.path)
      .then((jsonObj) =>{
        var products = [];
          for(var i=0; i<jsonObj.products.length; i++){
            var obj = {};
            obj._id = jsonObj[i]._id
            obj.seller_id = jsonObj[i].seller_id;
            obj.title = jsonObj[i].title;
            obj.description = jsonObj[i].description;
            obj.img = jsonObj[i].img;
            obj.status = jsonObj[i].status;
            obj.category = jsonObj[i].category;
            obj.productCategory = jsonObj[i].productCategory;
            obj.quantity = jsonObj[i].quantity;
            obj.price = jsonObj[i].price;
            products.push(obj);
          }
              Product.insertMany(products).then((function (){
                res.status(200).send({
                  message: "Successfully Uploaded!"
              }).catch(function(error){
                res.status(500).send({
                    message: "failure",
                    error
                });
               });
          }))
      }).catch((error) => {
        res.status(500).send({
            message: "failure",
            error
        });
    })
  });

Front.jsx

 const uploadCSVProduct = async (e) =>{
    e.preventDefault();
   const file = e.target[0]?.files[0]
   console.log(file)
   if(!file) return

   try {
    const res = await publicRequest.post('/product/addcsv')
    console.log(res.data)
   } catch (error) {
    console.log(error)
   }
}



<form onSubmit={uploadCSVProduct} className='form'>
    <input type='file' multiple />
    <Button variant='contained' endIcon={<PhotoCamera />}  size="small" 
     type='submit'>Upload</Button>
</form>
Zurcemozz
  • 183
  • 1
  • 9
  • What errors are you getting during the import, what is being logged to the console if you log `obj` after each iteration, what package are you using to parse the csv file. Perhaps this can help you : https://stackoverflow.com/a/51482528/15474532 – Ryan Zeelie Jan 15 '23 at 03:06

0 Answers0