问题
I have a local MySQL database mydb
. It contains a table called person
, with fields id
(primary key, integer auto-increment) and name
(text). The table contains records that I do not want to delete.
I want a LoopBack app that connects to mydb
through a data source myds
. The app should have a model Person
(which extends PersistedModel
). CRUD operations on the Person
model should be reflected on the people
table of mydb
.
How do I build the app?
回答1:
Generate an empty application with the application generator.
>lb
? What's the name of your application? myapp
? Enter name of the directory to contain the project: myapp
? Which version of LoopBack would you like to use? 3.x (current)
? What kind of application do you have in mind? empty-server
Add a new datasource:
/* /server/datasources.json */
"myds": {
"host": "localhost",
"port": 3306,
"url": "",
"database": "mydb",
"password": "password",
"name": "myds",
"user": "root",
"connector": "mysql"
}
Install loopback-connector-mysql:
> npm install loopback-connector-mysql --save
Create a model
/* /common/models/Person.json */
{
"name": "Person",
"plural": "People",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"id": {
"type": "number",
"required": true
},
"name": {
"type": "string"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Then attach the model to the data source.
/* /server/model-config.json */
{
// ...
"Person": {
"dataSource": "myds",
"public": true
}
//...
}
The app is complete. To run the app,
> node .
Then navigate to localhost:3000/explorer
in a browser. Click on the Person
model, then click on the route GET /People
, then click "try it out!" The app should return all rows in the person
table from the database. The other CRUD operations should also function properly.
Note that the naming is very important. When we connect a model named Person
and to the datasource myds
, which itself connects to the database mydb
, LoopBack looks for a table called Person
in mydb (this may interact with case-sensitivty of table names in your MySQL installation), with exactly the properties of Person
as its field names.
来源:https://stackoverflow.com/questions/51602168/connect-loopback-app-to-existing-mysql-database