agmission/Development/server/scripts/migrateAddresses.js

87 lines
2.8 KiB
JavaScript

'use strict';
const mongoose = require('mongoose');
const debug = require('debug')('agm:migrateAddresses');
const { DBConnection } = require('../helpers/db/connect.js'); // Database connection function
const models = require('../model/index.js'); // Load models
const utils = require('../helpers/utils.js');
// Parse command line arguments
const args = process.argv.slice(2);
const isDryRun = args.includes('--dry-run');
if (isDryRun) {
debug('Running in DRY-RUN mode - no changes will be made');
}
// Initialize database connection
const workerDB = new DBConnection('Address Migration Worker');
async function migrateAddresses() {
debug('Starting address migration...');
// Fetch customers with the old `billAddress` field and empty addresses array
const customers = await models.Customer.find({
billAddress: { $exists: true },
$or: [
{ addresses: { $exists: false } },
{ addresses: { $size: 0 } }
]
}).lean();
if (utils.isEmptyArray(customers)) {
debug('No customers found with the old `billAddress` field and empty addresses array.');
return;
}
debug(`Found ${customers.length} customers to migrate.`);
for (const customer of customers) {
try {
if (customer.billAddress) {
// Convert the single-line `billAddress` to the new `addresses` array format
const newAddress = {
...customer.billAddress, // Assuming `billAddress` has fields matching the new AddressSchema
isBilling: true // Mark as the current billing address
};
if (isDryRun) {
debug(`[DRY-RUN] Would migrate customer ID: ${customer._id}, username: ${customer.username}`);
debug(`[DRY-RUN] New address would be:`, JSON.stringify(newAddress, null, 2));
} else {
// Update the customer document
await models.Customer.updateOne(
{ _id: customer._id },
{
$set: { addresses: [newAddress] }, // Add the new `addresses` array
$unset: { billAddress: '' } // Remove the old `billAddress` field
}
);
debug(`Migrated addresses for customer ID: ${customer._id}, username: ${customer.username}`);
}
}
} catch (error) {
debug(`Error migrating addresses for customer ID: ${customer._id}, username: ${customer.username}`, error);
}
}
if (isDryRun) {
debug('Address migration DRY-RUN completed. No changes were made.');
} else {
debug('Address migration completed.');
}
}
// Initialize the database connection and start migration
workerDB.initialize({
setupExitHandlers: false,
onReady: async () => {
try {
await migrateAddresses();
process.exit(0);
} catch (error) {
debug('Migration failed:', error);
process.exit(1);
}
}
});