This repository was archived by the owner on Nov 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcleanup_duplicates.js
More file actions
84 lines (70 loc) · 2.71 KB
/
cleanup_duplicates.js
File metadata and controls
84 lines (70 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// cleanup_duplicates.js - Remove duplicate bus assignments
const mongoose = require('mongoose');
require('dotenv').config();
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI || 'mongodb://localhost:27017/sriexpress')
.then(() => {
console.log('Connected to MongoDB');
removeDuplicates();
})
.catch(err => {
console.error('MongoDB connection error:', err);
process.exit(1);
});
// Device Schema (simplified)
const DeviceSchema = new mongoose.Schema({
deviceId: String,
vehicleNumber: String,
vehicleType: String,
status: String,
isActive: Boolean,
createdAt: Date,
// ... other fields
}, { strict: false });
const Device = mongoose.model('Device', DeviceSchema);
async function removeDuplicates() {
try {
console.log('🔍 Finding duplicate vehicles...');
// Find all devices
const devices = await Device.find({ isActive: true }).sort({ createdAt: 1 });
console.log(`Found ${devices.length} active devices`);
// Group by vehicle number
const vehicleGroups = {};
devices.forEach(device => {
const vehicleNum = device.vehicleNumber;
if (!vehicleGroups[vehicleNum]) {
vehicleGroups[vehicleNum] = [];
}
vehicleGroups[vehicleNum].push(device);
});
// Find and remove duplicates
let duplicatesRemoved = 0;
for (const [vehicleNum, deviceList] of Object.entries(vehicleGroups)) {
if (deviceList.length > 1) {
console.log(`\n🚨 Found ${deviceList.length} duplicates for vehicle ${vehicleNum}:`);
// Keep the most recent one, remove the rest
const sortedDevices = deviceList.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
const keepDevice = sortedDevices[0];
const removeDevices = sortedDevices.slice(1);
console.log(` ✅ Keeping: ${keepDevice._id} (created: ${keepDevice.createdAt})`);
for (const device of removeDevices) {
console.log(` ❌ Removing: ${device._id} (created: ${device.createdAt})`);
await Device.findByIdAndUpdate(device._id, { isActive: false });
duplicatesRemoved++;
}
}
}
console.log(`\n✅ Cleanup complete! Removed ${duplicatesRemoved} duplicate devices.`);
// Show remaining devices
console.log('\n📊 Remaining active devices:');
const remainingDevices = await Device.find({ isActive: true }).sort({ vehicleNumber: 1 });
remainingDevices.forEach(device => {
console.log(` - Vehicle ${device.vehicleNumber} (${device._id}) - Status: ${device.status}`);
});
} catch (error) {
console.error('❌ Error during cleanup:', error);
} finally {
mongoose.connection.close();
process.exit(0);
}
}