【问题标题】:Can't insert JSON file into MongoDB's collection throught Node driver无法通过 Node 驱动程序将 JSON 文件插入 MongoDB 集合
【发布时间】:2021-09-01 18:15:46
【问题描述】:

我正在尝试从我的磁盘读取文件并将其推送到 MongoDB 的集合中,但连接在完成之前关闭并且我收到错误: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);

我做错了什么?

【问题讨论】:

    标签: node.js json mongodb


    【解决方案1】:

    在上述情况下,mongo 客户端将在 insertIntoCollection 函数触发之前关闭,因为它是一个 Promise 函数,并且 Promise 不会在 finally 触发之前结束。我希望下面的代码能够满足您的期望。

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      相关资源
      最近更新 更多