-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add confirmation date to validator and denormalise existing data on m…
…igration #1875
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
...-serving/scripts/setup-db/migrations/20211109102327-denormalise-confirmation-date-1875.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}}); | ||
} | ||
}; |