61 lines
1.9 KiB
JavaScript
61 lines
1.9 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');
|
|
|
|
// Initialize database connection
|
|
const workerDB = new DBConnection('Address Migration Worker');
|
|
|
|
async function migrateAddresses() {
|
|
debug('Starting address migration...');
|
|
|
|
// Fetch customers with the old `billAddress` field
|
|
const customers = await models.Customer.find({ billAddress: { $exists: true } }).lean();
|
|
|
|
if (utils.isEmptyArray(customers)) {
|
|
debug('No customers found with the old `billAddress` field.');
|
|
return;
|
|
}
|
|
|
|
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
|
|
};
|
|
|
|
// 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
|
|
}
|
|
);
|
|
}
|
|
} catch (error) {
|
|
debug(`Error migrating addresses for customer ID: ${customer._id}, username: ${customer.username}`, error);
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}); |