如何用Node.js的Mongoose与fs模块将文件夹中TXT文本存入MongoDB
使用Node.js的Mongoose和fs模块将TXT文件内容插入MongoDB
步骤1:安装依赖
首先确保安装Mongoose(fs是Node.js内置模块,无需额外安装):
npm install mongoose
步骤2:定义Mongoose数据模型
根据你的TXT内容结构,先定义MongoDB的数据模型。示例中假设你需要存储文件名和解析后的每行内容(按;拆分后的数组):
const mongoose = require('mongoose'); // 连接MongoDB数据库 mongoose.connect('mongodb://localhost:27017/your-database-name', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB连接成功')) .catch(err => console.error('MongoDB连接失败:', err)); // 定义数据Schema const TextRecordSchema = new mongoose.Schema({ fileName: { type: String, required: true }, // 存储TXT文件名 content: [{ type: Array }] // 存储每行拆分后的内容数组 }); // 创建数据模型 const TextRecord = mongoose.model('TextRecord', TextRecordSchema);
步骤3:完善文件读取与数据插入逻辑
你的现有代码存在异步回调顺序问题(硬编码读取单个文件、未遍历文件夹内所有TXT),改用Promise版fs和async/await可以更清晰地处理异步流程:
const fs = require('fs').promises; const path = require('path'); // 处理文件夹内所有TXT文件的异步函数 async function processTxtFiles(folderPath) { try { // 读取文件夹内所有文件 const files = await fs.readdir(folderPath); // 遍历每个文件,仅处理TXT格式 for (const file of files) { if (path.extname(file).toLowerCase() === '.txt') { const filePath = path.join(folderPath, file); // 读取文件内容 const fileContent = await fs.readFile(filePath, 'utf8'); // 解析内容:按行拆分,过滤空行,再按;拆分每行并去除多余空格 const parsedContent = fileContent.split('\n') .filter(line => line.trim() !== '') .map(line => line.split(';').map(item => item.trim())); // 创建数据库记录并保存 const newRecord = new TextRecord({ fileName: file, content: parsedContent }); await newRecord.save(); console.log(`文件 ${file} 内容已成功插入数据库`); } } console.log('所有TXT文件处理完成'); await mongoose.disconnect(); // 处理完成后关闭数据库连接 } catch (err) { console.error('处理过程中出错:', err); await mongoose.disconnect(); } } // 调用函数,传入你的TXT文件夹路径 processTxtFiles('D:/scnner_data/public');
自定义调整说明
如果你的TXT每行是固定结构的字段(比如字段1;字段2;字段3),可以修改Schema为具体字段,示例:
const TextRecordSchema = new mongoose.Schema({ fileName: String, field1: String, field2: String, field3: String }); // 解析时对应字段赋值 const parsedLines = fileContent.split('\n').filter(line => line.trim()); for (const line of parsedLines) { const [field1, field2, field3] = line.split(';').map(item => item.trim()); const newRecord = new TextRecord({ fileName: file, field1, field2, field3 }); await newRecord.save(); }
内容的提问来源于stack exchange,提问作者akasha sharma
相关产品推荐
相关产品推荐

