AutoCatBackend/migration.js

81 lines
2.7 KiB
JavaScript

import { MongoClient } from 'mongodb';
import { config } from 'dotenv';
import dotenvExpand from 'dotenv-expand';
let dotenvConf = config();
dotenvExpand(dotenvConf);
async function addUpdatedDate() {
let client = await MongoClient.connect(process.env.MONGO_CONNECTION_STRING);
let db = client.db('autocatdev');
let collection = db.collection('vehicles');
let vehicles = await collection.find().toArray();
for(let vehicle of vehicles) {
let updatedDate = vehicle.addedDate;
if(vehicle.events && vehicle.events.length > 0) {
let lastEvent = vehicle.events.reduce((acc, cur) => acc.date > cur.date ? acc : cur);
updatedDate = Math.max(1000*lastEvent.date, vehicle.addedDate);
}
console.log(updatedDate);
await collection.updateOne({ _id: vehicle._id }, { $set: { updatedDate } });
}
}
async function addDebugInfoStatus() {
let client = await MongoClient.connect(process.env.MONGO_CONNECTION_STRING);
let db = client.db('autocatdev');
let collection = db.collection('vehicles');
let vehicles = await collection.find().toArray();
for(let vehicle of vehicles) {
if(vehicle.debugInfo) {
for(const [providerName] of Object.entries(vehicle.debugInfo)) {
if(vehicle.debugInfo[providerName]) {
vehicle.debugInfo[providerName].status = vehicle.debugInfo[providerName].error == null ? 0 : 1;
}
}
await collection.updateOne({ _id: vehicle._id }, { $set: { debugInfo: vehicle.debugInfo } });
}
}
}
async function fixNullEvents() {
let client = await MongoClient.connect(process.env.MONGO_CONNECTION_STRING);
let db = client.db('autocatdev');
let collection = db.collection('vehicles');
let vehicles = await collection.find().toArray();
for(let vehicle of vehicles) {
if(vehicle.events == null) {
//console.log(vehicle.events);
await collection.updateOne({ number: vehicle.number }, { $set: { events: [] } });
}
}
}
async function fixNullNotes() {
let client = await MongoClient.connect(process.env.MONGO_CONNECTION_STRING);
let db = client.db('autocatdev');
let collection = db.collection('vehicles');
let vehicles = await collection.find().toArray();
for(let vehicle of vehicles) {
if(vehicle.notes == null) {
//console.log(vehicle.events);
await collection.updateOne({ number: vehicle.number }, { $set: { notes: [] } });
}
}
}
async function fixNullOsagoContracts() {
let client = await MongoClient.connect(process.env.MONGO_CONNECTION_STRING);
let db = client.db('autocatdev');
let collection = db.collection('vehicles');
await collection.updateMany({ osagoContracts: null }, { $set: { osagoContracts: [] } });
}
(async () => {
//await addUpdatedDate();
//await addDebugInfoStatus();
//await fixNullNotes();
await fixNullOsagoContracts();
console.log('====== Done ======');
})();