Created
March 8, 2016 03:02
-
-
Save alFReD-NSH/56aa033b362f1dbc9ceb to your computer and use it in GitHub Desktop.
For those using loopback and changing their database from one to another. This will copy all the data from the given database to the configured database(in server/datasources). This was tested to copy from postgresql to mongodb.
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
'use strict'; | |
let app = require('../server/server'); | |
let loopback = require('loopback'); | |
let prompt = require('prompt'); | |
console.log(`This will copy all the data from the given database to the | |
configured database(in server/datasources)`) | |
prompt.get(['connector', 'url'], (err, result) => { | |
if (err) { | |
throw err; | |
} | |
let ds = app.dataSource('remote', result); | |
let models = new Set(); | |
app.models().forEach(Model => { | |
if (isPersisted(Model)) { | |
models.add(Model); | |
for (let relation in Model.relations) { | |
let ModelThrough = Model.relations[relation].modelThrough; | |
if (ModelThrough && isPersisted(ModelThrough)) { | |
models.add(ModelThrough); | |
} | |
} | |
} | |
}); | |
function isPersisted(Model) { | |
return Model.getDataSource() && Model.find; | |
} | |
Promise.all(Array.from(models).map(Model => { | |
let RemoteModel = Model.extend(Model.modelName, {}); | |
RemoteModel.attachTo(ds); | |
return RemoteModel.find() | |
.then(instances => | |
// We can't just call Model.create on the array because it will not | |
// return a promise in that case | |
Promise.all(instances.map((instance) => Model.create(instance)))) | |
.catch(err => { | |
console.error('I got an error for copying the data of', Model.modelName); | |
console.error(err); | |
console.error(err.stack); | |
}); | |
})).then(() => process.exit()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment