Skip to content

Instantly share code, notes, and snippets.

@alFReD-NSH
Created March 8, 2016 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alFReD-NSH/56aa033b362f1dbc9ceb to your computer and use it in GitHub Desktop.
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.
'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