Create a MongoDB DataSource in LoopBack

Bram Borggreve
InstructorBram Borggreve

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

In this lesson we will create a dynamic datasource in LoopBack. If the API is started with the environment variable MONGODB_URL it will use this url and the loopback-connector-mongodb package to store the data in MongoDB.

In the course we will use a local MongoDB instance. If you don't have MongoDB running locally you can always create a free MongoDB Atlas database.

[00:00] In our server folder, we create a file, datasources.local.js. In this file, we can dynamically control our data sources.

[00:09] We start by adding a const called mongodburl = process.env.mongodb_url. This allows us to control the MongoDB URL with an environment variable.

[00:22] 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.

[00:41] 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.

[00:53] 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.

[01:11] 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.

[01:26] 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.

[01:35] 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.