mongoose 如何在没有mongoimport的情况下从JS/node中的JSON文件的文件路径种子MongoDB数据库

qcbq4gxm  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(106)

如何编写一个CLI函数,让用户提供JSON种子文件的文件路径,以便填充MongoDB数据库?
例如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);

字符串

hfwmuf9z

hfwmuf9z1#

使用mongoDB包的解决方案: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);

字符串
使用mongoose包的解决方案: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);

相关问题