Last active
January 16, 2019 23:02
-
-
Save bmorrisondev/193002688d29d029823974aff10f0d9f to your computer and use it in GitHub Desktop.
Migrate MongoDB Collections using Mongoose.js
This file contains hidden or 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
const fs = require('fs') | |
const mongoose = require('mongoose') | |
const ModelOne = require('./models/ModelOne') | |
const ModelTwo = require('./models/ModelTwo') | |
let source = "mongodb://source.database.com:27017/srcdb" | |
let destination = "mongodb://dest.database.com:27017/dstdb" | |
let models = [ | |
ModelOne, | |
ModelTwo | |
] | |
migrateDbs (sourceConnectionString, destinationConnectionString, dataMap) | |
async function migrateDbs (source, destination, dataMap) { | |
await exportDbToJson(source, dataMap) | |
await importJsonIntoDestination(destination, dataMap) | |
} | |
async function exportDbToJson (source, models) { | |
let sourceConnection = await mongoose.connect(source, { useNewUrlParser: true}) | |
for(let i = 0; i < models.length; i++) { | |
let data = await models[i].find({}) | |
await writeDataToFile(models[i].modelName, data) | |
} | |
sourceConnection.connection.close() | |
} | |
async function importJsonIntoDestination (destination, models) { | |
let destinationConnection = await mongoose.connect(destination, { useNewUrlParser: true }) | |
for(let i = 0; i < models.length; i++) { | |
let data = await getDataFromFile(models[i].modelName) | |
await models[i].create(data) | |
} | |
destinationConnection.connection.close() | |
} | |
function getDataFromFile (modelName) { | |
return new Promise((resolve, reject) => { | |
let filename = `./data/${modelName}.json` | |
fs.readFile(filename, 'utf8', function (err, data) { | |
if (err) reject(err) | |
resolve(JSON.parse(data)) | |
}) | |
}) | |
} | |
function writeDataToFile (modelName, data) { | |
return new Promise((resolve, reject) => { | |
if (!fs.existsSync('./data')) { | |
fs.mkdirSync('./data'); | |
} | |
let filename = `./data/${modelName}.json` | |
fs.writeFile(filename, JSON.stringify(data), 'utf8', err => { | |
if(err) reject(err) | |
resolve() | |
}) | |
}) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment