I am new to Loopback framework.
I have gone through getting started and model creation and tried creating test application.
I created application by command -> lb
and created mysql datasource by -> lb datasource
and created two models by -> lb model
which are using mysql datasource.
{
"name": "Brand",
"plural": "brands",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
so now when I start application by npm start
and goto localhost:3000/explorer
and try using any end point, I get following table not found error.
Unhandled error for request GET /api/brands: Error: ER_NO_SUCH_TABLE: Table 'loop3.Brand' doesn't exist
Does Loopback auto creates tables in database ?? Or I will have to create autoMigrate
file for every model Or how it should be done please help..
Answer:
thanks to @Diana, I created script.js
file in boot
directory and added following code
'use strict';
module.exports = function(app) {
var db = app.datasources.mysqld;
db.autoupdate(function(err) {
if (err) throw err;
console.log('\nAutomigrate completed');
// other code here
});
};
It creates table as well as updates if any property has changed.
You need to run the automigrate
function to create the table schema in the database. You can add this in the boot script that it will get run every time you start the application. See this as an example:
https://github.com/ssh24/loopback-sandbox/blob/master/apps/mysql/mysql-101/server/boot/script.js
Please note that the automigrate
function will drop the existing table and create it again. It means any existing data will be lost. autoupdate
function can be used instead. See this documentation page for details: https://loopback.io/doc/en/lb3/Creating-a-database-schema-from-models.html.