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

42 lines
1.5 KiB
JavaScript

const mongoose = require('mongoose');
const connectDB = require('../config/db');
const Scene = require('../models/Scene');
/**
* Script sửa lỗi các Scene mồ côi (không có tourId)
* Logic: Nếu một Scene không có tourId, nó sẽ được gán tourId = _id (trở thành Root)
*/
const fixOrphans = async () => {
try {
await connectDB();
// Sử dụng logic quét rộng tương tự audit script để tìm tất cả các loại "rác" tourId
const allScenes = await Scene.find({});
const orphans = allScenes.filter(s =>
!s.tourId ||
s.tourId === "" ||
s.tourId === "null" ||
s.tourId === "undefined"
);
console.log(`Tìm thấy ${orphans.length} scene mồ côi. Đang xử lý...`);
for (const scene of orphans) {
// [FIX] Sử dụng updateOne trực tiếp trên collection để bypass Schema validation
// Đảm bảo dữ liệu CHẮC CHẮN được ghi xuống Database
await Scene.collection.updateOne(
{ _id: scene._id },
{ $set: { tourId: scene._id } }
);
console.log(`- [FIXED] Scene: ${scene.name || scene.title} (ID: ${scene._id}) -> Đã trở thành Tour Gốc`);
}
console.log('\n--- HOÀN TẤT SỬA LỖI DỮ LIỆU ---');
mongoose.connection.close();
} catch (err) {
console.error('Lỗi thực thi:', err);
process.exit(1);
}
};
fixOrphans();