agmission/Development/server/workers/migrateAddresses.js

57 lines
1.8 KiB
JavaScript

'use strict';
const mongoose = require('mongoose');
const debug = require('debug')('agm:migrateAddresses');
const dbConn = require('../helpers/db/connect.js')(); // Ensure DB connection
const models = require('../model/index.js'); // Load models
const utils = require('../helpers/utils.js');
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.');
}
(async function main() {
dbConn.once('open', async () => {
try {
await migrateAddresses();
} catch (error) {
console.error('Migration failed:', error);
} finally {
mongoose.connection.close(); // Close the DB connection
process.exit();
}
});
})();