我目前正在使用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 ?