Spaces:
Running
Running
| const fs = require('fs'); | |
| const mongoose = require('mongoose'); | |
| const dotenv = require('dotenv'); | |
| const Product = require('../models/productModel'); | |
| const Category = require('../models/categoryModel'); | |
| const Provider = require('../models/providerModel'); | |
| dotenv.config({ path: './config.env' }); | |
| const DB = process.env.DATABASE.replace( | |
| '<PASSWORD>', | |
| process.env.DATABASE_PASSWORD, | |
| ); | |
| mongoose | |
| .connect(DB) | |
| .then(() => console.log('DB connection successful!')) | |
| .catch((err) => { | |
| console.log('DB connection error:', err); | |
| }); | |
| // Read JSON file | |
| const products = JSON.parse( | |
| fs.readFileSync(`${__dirname}/products-sample.json`, 'utf-8'), | |
| ); | |
| // Import data into DB | |
| const importData = async () => { | |
| try { | |
| await Product.create(products); | |
| console.log('Data successfully loaded!'); | |
| } catch (err) { | |
| console.log(err); | |
| } | |
| process.exit(); | |
| }; | |
| // Delete all data from DB | |
| const deleteData = async () => { | |
| try { | |
| await Product.deleteMany(); | |
| await Category.deleteMany(); | |
| await Provider.deleteMany(); | |
| console.log('Data successfully deleted!'); | |
| } catch (err) { | |
| console.log(err); | |
| } | |
| process.exit(); | |
| }; | |
| if (process.argv[2] === '--import') { | |
| importData(); | |
| } else if (process.argv[2] === '--delete') { | |
| deleteData(); | |
| } | |