In our server folder, we create a file, datasources.local.js. In this file, we can dynamically control our data sources.
We start by adding a const called mongodburl = process.env.mongodb_url. This allows us to control the MongoDB URL with an environment variable.
We then add an If statement that checks if the variable is set, and if so, will print the URL. To see if this works, we'll start our server, prefixed by the mongodb_url environment variable. In this case, I entered a URL to a MongoDB server that I have running on localhost.
To connect to the actual database, we need to pass in the database configuration. We create a const. called DataSources, which is an object with a key of DB, which is a reference to our data source.
We define an object with three keys. For name, we use DB. For connector, we use MongoDB. For the URL, we pass in a local reference to our environment variable. The last thing to do is to export our data sources using module.exports = datasources.
When our server restarts, we see that we get an error message. LoopBack tells us that it cannot create a DataSource DB because the MongoDB connector is not installed. Luckily, it also gives us a command to fix it. Let's run that command.
When the connector has installed this dependency, and we start the server again, we see that it now starts as expected, and that it connects to MongoDB.
If you tried to connect to a non-existing MongoDB server, you'll get an error message as well. Make sure you connect to a server that exists and that is accessible.