// tslint:disable:no-console import * as moment from 'moment'; import * as mongoose from 'mongoose'; import { chevre } from '../../../lib/index'; // const project = { id: String(process.env.PROJECT_ID) }; async function main() { await mongoose.connect(process.env.MONGOLAB_URI); const eventRepo = new chevre.repository.Event(mongoose.connection); const productRepo = new chevre.repository.Product(mongoose.connection); const cursor = eventRepo.getCursor( { // 'project.id': { $eq: project.id }, 'project.id': { $ne: '' }, typeOf: { $eq: chevre.factory.eventType.ScreeningEvent }, startDate: { $gte: moment() .add(-1, 'month') .toDate() } // _id: { $eq: 'al6afd7np' } }, { // _id: 1, } ); console.log('events found'); let i = 0; let updateCount = 0; await cursor.eachAsync(async (doc) => { i += 1; const event: chevre.factory.event.screeningEvent.IEvent = doc.toObject(); const itemOfferedId = (event.offers)?.itemOffered?.id; const itemOfferedName = (event.offers)?.itemOffered?.name?.ja; if (typeof itemOfferedName === 'string' && itemOfferedName.length > 0) { console.log( 'already exist...', event.project.id, event.id, event.startDate, itemOfferedId, i); } else { const existingProducts = await productRepo.search({ limit: 1, page: 1, project: { id: { $eq: event.project.id } }, id: { $eq: itemOfferedId } }); const existingProduct = existingProducts.shift(); if (existingProduct === undefined) { // throw new Error(`product not found ${event.id}`); // no op } else { const newItemOfferedName: string = (typeof existingProduct.name === 'string') ? existingProduct.name : String(existingProduct.name?.ja); console.log( 'updating event...', event.project.id, event.id, event.startDate, itemOfferedId, newItemOfferedName, i); await eventRepo.updatePartiallyById({ id: event.id, attributes: { typeOf: event.typeOf, 'offers.itemOffered.name': { ja: newItemOfferedName } } }); } updateCount += 1; console.log( 'updated', event.project.id, event.id, event.startDate, itemOfferedId, i); } }); console.log(i, 'events checked'); console.log(updateCount, 'events updated'); } main() .then() .catch(console.error);