How to seed a MongoDB database from a JSON file's file path in JS/node without mongoimport

110 views Asked by At

How to write a CLI function that will let the user provide a file path to a JSON seed file in order to populate a MongoDB database?

e.g. node ./command.js seed ./seedfile.json

const program = require('commander');

    program
        .command('seed <filePath>')
        .alias('s')
        .description('Automatically add many entries from a json file')
        .action(answer => seedEntries(answer)
        );


const seedEntries = async (filePath) => {
     //What to put here to get mongodb to accept the entries?
    }
};

program.parse(process.argv);
1

There are 1 answers

0
windsy On BEST ANSWER

Solution using mongoDB package: npm i mongodb

const program = require('commander');
//add some requirements for the package and filesystem and path modules
const { MongoClient } = require('mongodb');
const fs = require("fs");
const path = require('path');

program
    .command('seed <filePath>')
    .alias('s')
    .description('Automatically add many entries from a JSON file')
    .action(filePath => addEntries(filePath));

const addEntries = async (filePath) => {
    //Create our client
    const client = new MongoClient('mongodb://localhost:27017/')
    try {
        const absolutePath = path.join(process.cwd(), filePath);
        const jsonData = JSON.parse(await fs.promises.readFile(absolutePath, 'utf-8'));

        //Connect our client and define our database pathway
        await client.connect();
        const database = client.db('NewDatabaseName');
        const collection = database.collection('Items');
        // Insert the entry data into the "items" collection
      await collection.insertMany(jsonData);
              // Log a success message that shows the number of new entries
      console.info('Number of new items added:', jsonData.length);

    } catch (error) {
        // Handle errors
        console.error('There was an error:', error);
    } finally {
        // Close the connection
        await client.close();
    }
};

program.parse(process.argv);

Solution using the mongoose package: npm i mongoose

const program = require('commander');
//add some requirements for the package and filesystem and path modules
const mongoose = require('mongoose');
const fs = require('fs').promises;
const path = require('path');

// Define the schema
const itemSchema = mongoose.Schema({
    carColor: { type: String, required: true },
    carBrand: { type: String, required: true },
});

program
    .command('seed <filePath>')
    .alias('s')
    .description('Automatically add many entries from a JSON file')
    .action(filePath => addEntries(filePath));

const addEntries = async (filePath) => {
    try {
        const absolutePath = path.join(process.cwd(), filePath);
        console.info('Attempting to read file at path:', absolutePath);
        const jsonData = JSON.parse(await fs.readFile(absolutePath, 'utf-8'));

        // Connect to the MongoDB URL and database
        await mongoose.connect('mongodb://localhost:27017/NewDatabaseName');

        // Create a model based on the schema
        const Item = mongoose.model('Item', itemSchema);

        // Insert the entry data into the "items" collection
        const result = await Item.insertMany(jsonData);

        // Log a success message that shows the number of new entries
        console.info('Number of new items added:', jsonData.length);
    } catch (error) {
        // Handle errors
        console.error('There was an error:', error);
    } finally {
        // Close the Mongoose connection
        await mongoose.connection.close();
    }
};

program.parse(process.argv);