我目前正在使用React和Mongoose(MongoDB)开发一个应用程序,我上传了一个文本文件,其中包含大约9000多行JSON.每一行都很重要,我需要能够将其存储在数据库中,以便以后访问.

我设置了两个函数,一个读取文件,另一个 for each 请求创建一个模型并将其保存到MongoDB.

Function to read each line

const createAndReadFile = async (filePath) => {
    //create a read stream of the File
    let fileStream = fs.createReadStream(filePath, 'utf8');

    const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity
    });

    for await (const line of rl) {
        let parsedJSONLine = JSON.parse(line);
            createAndAddToDB(parsedJSONLine);
    }
};

Function to add to the database each line

const createAndAddToDB = async (jsonRequest) => {
    try {
        let request = new Request(jsonRequest);

        await request.save();
    } catch (error) {}
};

My question is, what's the most effective way to wait until all the lines have been converted to a model and saved in the database ?

推荐答案

使用Promise.all等待在for await循环中创建的所有promise 的解决:

var promises = [];
for await (const line of rl) {
  let parsedJSONLine = JSON.parse(line);
  promises.push(createAndAddToDB(parsedJSONLine));
}
return Promise.all(promises);

或者,您可以在for await循环中执行转换,并批量写入数据库:

var promises = [];
for await (const line of rl) {
  let parsedJSONLine = JSON.parse(line);
  promises.push(convertToDBFormat(parsedJSONLine));
}
return Promise.all(promises).then(function(converted) {
  return addToDBBatch(converted);
});

Node.js相关问答推荐

链接Inbox类方法,范围在哪里以及为什么发生变化?

Spotify Auth访问令牌给出错误代码400

当建议在第二代上运行云功能时,现在是否有新的Firestore AdminClient可供使用?

无法从ejs Web应用程序中的正文中提取数据

仅在一次查询中 MongoDB 上最近的一对位置

TS[2339]:类型 '() => Promise<(Document & Omit) | 上不存在属性空>'

与诗乃一起嘲笑奈克斯

我如何保护nodejs中的路由

Jest - SyntaxError: 不能在@nestjs/axios 的模块外使用 import 语句

我误解了外键的工作原理吗?使用续集

处理 UTC 日期和future

如何在 MongoDB collection.find() 上获取回调

如何获取在 NodeJS 中执行的脚本的文件名?

适用于 Windows 的 NVM 无法正常工作?

在 Jade 包含中使用变量

mongo 可以 upsert 数组数据吗?

从 React(同构应用程序)进行 API 调用时出现Access-Control-Allow-Origin问题

Javascript在try块内设置const变量

如何调试 Gulp 任务?

FireStore 如果不存在则创建一个文档