DEV Community

Visakh Vijayan
Visakh Vijayan

Posted on

Backfilling customer plans with JS and Mongo

Here is another of those days when we saved our time drastically. We introduced a feature called plans for our customers. The product now had two plans - STANDARD and PREMIUM. But we had to backfill data for all the organisations now. That was going to be a headache.

We could either write a script that could do this. But that meant checking the code into the repository. We wanted an easier way since the new feature was already in production.

Luckily we use mongoDb and mongo has a JS shell. And so this is the magic that worked for us -

db.getCollection('organizations').find({})
.forEach(function(organization) {

    const existingPlan = db
    .getCollection('organization-subscription-plans')
    .findOne({ 
        _id: organization._id, 
        planId: <id>, 
        status: <status> 
    });

    if (!existingPlan) {
        db.getCollection('organization-subscription-plans')
        .insertOne({
            organizationId: organization._id,
            planId: <id>,
            status: <status>,
            startDate: <date>,
            expirationDate: <date>
        });
    }
});

Enter fullscreen mode Exit fullscreen mode

And before you know it, all our customers were welcomed into our base plan. Yippeee!!!

P.S. Use the Mongo Compass shell if you have a lot of data as RoboMongo keeps erroring out on timeout.

Top comments (1)

Collapse
 
aadilmughal786 profile image
Aadil Mugal

Nice 👍