Skip to content

Commit

Permalink
Add confirmation date to validator and denormalise existing data on m…
Browse files Browse the repository at this point in the history
…igration #1875
  • Loading branch information
iamleeg committed Nov 12, 2021
1 parent 7964bae commit 6138fcd
Showing 1 changed file with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const confirmationDate = {
bsonType: "date",
};

module.exports = {
async up(db, client) {
let res = await db.command({listCollections: undefined, filter: {name: 'cases'}});
let schema = res.cursor.firstBatch[0].options.validator.$jsonSchema;
schema.properties.confirmationDate = confirmationDate;
await db.command({ collMod: 'cases', validator:{ $jsonSchema: schema } } );

// now amend the existing cases. This must be done one by one so will take a lot of time!
const collection = db.collection('cases');
collection.find({}).forEach(function(err, doc) {
if(!doc) {
console.error(`error ${err} migrating confirmation date on doc ${doc?._id ?? ''}`);
// continue as subsequent case modifications may still work
return;
}
doc.events.forEach((anEvent) => {
if (anEvent.name === 'confirmed') {
const confirmationDate = anEvent.dateRange.start;
collection.updateOne({ _id: doc._id }, { confirmationDate });
return;
}
});
});
},

async down(db, client) {
let res = await db.command({listCollections: undefined, filter: {name: 'cases'}});
let schema = res.cursor.firstBatch[0].options.validator.$jsonSchema;
delete schema.properties.confirmationDate;
await db.command( { collMod: 'cases', validator:{ $jsonSchema: schema } } );

const collection = db.collection('cases');
collection.updateMany({}, {$unset: {"confirmationDate":1}});
}
};

0 comments on commit 6138fcd

Please sign in to comment.