【发布时间】: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);
我做错了什么?
【问题讨论】: