Files
3dtours/backend/scripts/fixAssetFileSize.js
T

66 lines
2.4 KiB
JavaScript

const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
const connectDB = require('../config/db');
const Asset = require('../models/Asset');
/**
* Script cập nhật bổ sung trường fileSize cho các Asset cũ
* Giúp tối ưu hóa việc kiểm tra Quota và thống kê dung lượng
*/
const fixAssetFileSize = async () => {
try {
console.log('=== BẮT ĐẦU CẬP NHẬT KÍCH THƯỚC FILE CHO ASSET ===');
await connectDB();
// 1. Tìm các Asset chưa có trường fileSize hoặc fileSize bằng null/0
const assetsToFix = await Asset.find({
$or: [
{ fileSize: { $exists: false } },
{ fileSize: null },
{ fileSize: 0 }
]
});
console.log(`- Tìm thấy ${assetsToFix.length} bản ghi cần cập nhật.`);
let successCount = 0;
let errorCount = 0;
let missingFileCount = 0;
for (const asset of assetsToFix) {
if (asset.filePath && fs.existsSync(asset.filePath)) {
try {
const stats = fs.statSync(asset.filePath);
asset.fileSize = stats.size;
await asset.save();
successCount++;
if (successCount % 10 === 0) {
console.log(` [Progress] Đã cập nhật ${successCount} file...`);
}
} catch (err) {
console.error(` [Lỗi] Không thể đọc stats cho Asset ${asset._id}: ${err.message}`);
errorCount++;
}
} else {
console.warn(` [Cảnh báo] Không tìm thấy file vật lý cho Asset ${asset._id}: ${asset.filePath}`);
missingFileCount++;
}
}
console.log('\n=== TỔNG KẾT QUÁ TRÌNH ===');
console.log(`- Thành công: ${successCount}`);
console.log(`- Lỗi đọc file: ${errorCount}`);
console.log(`- File không tồn tại trên đĩa: ${missingFileCount}`);
console.log('==========================================');
mongoose.connection.close();
process.exit(0);
} catch (error) {
console.error('Lỗi nghiêm trọng:', error.message);
process.exit(1);
}
};
fixAssetFileSize();