Can't insert JSON file into MongoDB's collection throught Node driver

Viewed 59

I'm trying to read files from my disk and push it into MongoDB's collections, but connection closing before it done and I get error: MongoError: Topology is closed, please connect.

async function launch() {
  try {
    await mongo.connect();
    console.log("Connection established");

    const database = mongo.db('task');

    const firstCol = database.collection('first');
    const secondCol = database.collection('second');

    const insertIntoCollection = async (file, col) => {
            fs.readFile(file, async function(err, data) {
                if (err) throw err;

                const json = JSON.parse(data);

                const result = await col.insertMany(json);

                console.log(result.insertCount);
            });
    }

        await insertIntoCollection('data/first.json', firstCol);
        await insertIntoCollection('data/second.json', secondCol);
    } finally {
    await mongo.close();
  }
}

launch().catch(console.dir);

What am I doing wrong?

1 Answers

In the above case mongo client will close before the insertIntoCollection function trigger since it is a promise function and promise will not over before the finally trigger.I hope below code will fulfil your expectations.

async function launch() {
    try {
        await mongo.connect();
        console.log("Connection established");

        const database = mongo.db('task');

        const firstCol = database.collection('first');
        const secondCol = database.collection('second');


        const insertIntoCollection = async (file, col) => {
            return new Promise((resolve, reject) => {
                fs.readFile(file, async (err, data) => {
                    try {
                        if (err) reject(err);
                        const json = JSON.parse(data);
                        const result = await col.insertMany(json);
                        console.log(result.insertCount);
                        resolve(result.insertCount)
                    } catch (err) {
                        reject(err)
                    }
                });
            })
        }
        await insertIntoCollection('data/first.json', firstCol);
        await insertIntoCollection('data/second.json', secondCol);
    } finally {
        await mongo.close();
    }
}

launch().catch(console.dir);
Related