43 lines
1.3 KiB
JavaScript
Raw Normal View History

2021-03-02 17:09:35 +01:00
'use strict';
2021-03-11 10:41:35 +01:00
const { shouldBeProcessed, getUpdatesInfo } = require('./utils');
2021-03-02 17:09:35 +01:00
const BATCH_SIZE = 1000;
const migrateForMongoose = async ({ model, attributesToMigrate, locales }) => {
const processedLocaleCodes = [];
for (const locale of locales) {
let batchCount = BATCH_SIZE;
let lastId;
while (batchCount === BATCH_SIZE) {
const findParams = { locale: locale.code };
if (lastId) {
findParams._id = { $gt: lastId };
}
const batch = await model
.find(findParams, [...attributesToMigrate, 'locale', 'localizations'])
2021-03-11 10:41:35 +01:00
.populate('localizations', 'locale id')
2021-03-02 17:09:35 +01:00
.sort({ _id: 1 })
.limit(BATCH_SIZE);
if (batch.length > 0) {
lastId = batch[batch.length - 1]._id;
}
batchCount = batch.length;
2021-03-11 10:41:35 +01:00
const entriesToProcess = batch.filter(shouldBeProcessed(processedLocaleCodes));
2021-03-02 17:09:35 +01:00
2021-03-11 10:41:35 +01:00
const updatesInfo = getUpdatesInfo({ entriesToProcess, attributesToMigrate });
2021-03-02 17:09:35 +01:00
const updates = updatesInfo.map(({ entriesIdsToUpdate, attributesValues }) => ({
updateMany: { filter: { _id: { $in: entriesIdsToUpdate } }, update: attributesValues },
}));
await model.bulkWrite(updates);
}
processedLocaleCodes.push(locale.code);
}
};
module.exports = migrateForMongoose;