Reversing MongoDB Migration to unset fields

Viewed 95

Say I'm trying to unset all foo fields in a Collection where foo:'bar'.

Collection.update({foo:'bar'}, {$unset:{foo:1}});

I want to try using https://atmospherejs.com/percolate/migrations.

My question is about how one would go about reverting that in a down function.

The selector for {foo:'bar'} won't match on anything anymore as those fields are removed.

The only thing I can think of is something like

#1. Save all _ids somewhere first

const idsOfFoosToBeUnset = Collection.find({foo:'bar'},{fields: {_id:1}}).fetch().map(doc => doc._id);
fs.writeFileSync('idsOfFoosToBeUnset.json', JSON.stringify(idsOfFoosToBeUnset), 'utf-8');

Actual down function

const idsToBeReset = JSON.parse(fs.readFileSync('idsOfFoosToBeUnset.json', 'utf-8');
Collection.update({_id: {$in:idsToBeReset }}, {$set: {foo: 'bar'}});

I'm just not a fan of having to save the _ids somewhere and then having to re-import in the down function.

Anybody else think of something cleaner?

0 Answers
Related