How to automigrate in Loopback
Two problems.
First, you are showing an Angular client-side error, while your problem is with the server side.
Now, back to the core of the problem.
A boot script must export a single function, that will accept either just the loopback object (your server) in the case of synchronous boot scripts, or the loopback object and a callback (for asynchronous boot scripts).
Writing boot scripts is documented here
The function datasource.automigrate
can be called synchronously. If you call it without parameters, by default it will execute for all models in your app, which is most likely what you want.
So, if the database you defined has for name mysql
(defined in ./server/datasources.json
) the boot script is :
module.exports = function (app) {
app.dataSources.mysql.automigrate();
console.log("Performed automigration.");
}
You can check that this works by running node .
and NOT by going in your browser at the adress the server is listening. (Your Angular-related error has nothing to do with the boot script, it is related to client-side files, most likely located in the client
folder).
It should display in the terminal
Performed automigration.
I really liked how Jesé Rodríguez's answer runs autoupdate on each model one at a time so I can know which ones were updated. Unfortunately it iterates over app.model
which is incorrect and can have some negative side effects.
Here's my version (requires Node 8+ for async/await):
'use strict';
// Update (or create) database schema (https://loopback.io/doc/en/lb3/Creating-a-database-schema-from-models.html)
// This is effectively a no-op for the memory connector
module.exports = function(app, cb) {
updateDatabaseSchema(app).then(() => {
process.nextTick(cb);
});
};
async function updateDatabaseSchema(app) {
const dataSource = app.dataSources.db;
for (let model of app.models()) {
if (await doesModelNeedUpdate(dataSource, model.modelName) === true) {
await updateSchemaForModel(dataSource, model.modelName);
}
}
}
function doesModelNeedUpdate(dataSource, model) {
return new Promise((resolve, reject) => {
dataSource.isActual(model, (err, actual) => {
if (err) reject(err);
resolve(!actual);
});
});
}
function updateSchemaForModel(dataSource, model) {
return new Promise((resolve, reject) => {
dataSource.autoupdate(model, (err, result) => {
if (err) reject(err);
console.log(`Autoupdate performed for model ${model}`);
resolve();
});
});
}