Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create a MongoDB DataSource in LoopBack


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.