Skip to content

Instantly share code, notes, and snippets.

@mayorcoded
Created June 29, 2020 13:32
Show Gist options
  • Save mayorcoded/48cf90e0778db77756f143ab4f72e97c to your computer and use it in GitHub Desktop.
Save mayorcoded/48cf90e0778db77756f143ab4f72e97c to your computer and use it in GitHub Desktop.
require('dotenv').config();
const mongodbUri = require('mongodb-uri');
const {MongoClient} = require('mongodb');
async function runMigration(){
const uri = process.env.DATABASE_URL;
const uriObject = mongodbUri.parse(uri);
const client = new MongoClient(uri,{ useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
const updatedSchema = await updateAccountSchema(client, uriObject.database);
if(updatedSchema){
console.log('The migration was successfully executed');
}
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
async function updateAccountSchema(client, database) {
const accounts = await client.db(database).collection('accounts');
const session = client.startSession();
const transactionOptions = {
readPreference: 'primary',
readConcern: { level: 'local' },
writeConcern: { w: 'majority' }
};
return new Promise(( async (resolve, reject) => {
await session.withTransaction( async () => {
const updatedAccounts = await accounts.updateMany(
{
balance: { $type: ["double", "int", "decimal"] },
ngntBalance : { $exists: true }
},
[
{$set: {
balance: {
ETH: "$balance",
NGNT: "$ngntBalance"
}
}},
{$unset: ['ngntBalance']}
]
);
if(updatedAccounts.result.ok){
resolve(updatedAccounts.result.ok)
}else{
reject(result.ok);
}
}, transactionOptions);
}))
}
runMigration().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment