Databases ​
Connection ​
Depending on the SQL database you selected, a src/<database>.ts
file will be created that sets up a connection using KnexJS. It uses the connection settings from the <database>
configuration value and exports a configure function that initializes the database connection. The Knex connection object is then accessible wherever you have access to the app object via
const knex = app.get('<database>Client')
The database pool size can be set in the configuration like this:
"postgresql": {
"client": "pg",
"connection": "<pg connection string>",
"pool": {
"min": 0,
"max": 7
}
},
connection
can also be an object instead of a connection string:
"postgresql": {
"client": "pg",
"connection": {
"host": "localhost",
"port": 5432,
"user": "postgres",
"password": "postgres",
"database": "pgtest"
}
}
src/mongodb.ts
exports a configure function that connects to the MongoDB connection string set as mongodb
in your configuration. The MongoDB NodeJS client is then accessible wherever you have access to the app object via
const db = await app.get('mongodbClient')
The default connection string tries to connect to a local MongoDB instance with no password. To use e.g. MongoDB Atlas change the mongodb
property in config/default.json
or add it as an environment variable with the connection string that will look similar to this:
mongodb+srv://<user>:<password>@cluster0.xyz.mongodb.net/?retryWrites=true&w=majority
Models ​
KnexJS does not have a concept of models. Instead a new service is initialized with the table name and app.get('<database>Client')
as the connection. For more information on how to create custom queries and more, see the SQL database adapter API documentation.
The collection for a MongoDB service can be accessed via
const userCollection = await app.service('users').getModel()
See the MongoDB service API documentation for more information.