node.jsmongodb

MONGODB_URI is undefined


Trying to make a Facebook chat bot following this guide: https://medium.com/@viviancpy/part-1-facebook-chatbot-with-heroku-webhook-b14090a136c7

I have no experience with node and JavaScript at all, mainly just Python. So I simply copy pasted the code from GitHub, but when I try to run it (as described in Step 4, with "yarn start") I get this error:

MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.

So I had a look at the code and found this:

const MONGODB_URI = process.env.MONGODB_URI;
var db = mongoose.connect(MONGODB_URI);

So in Python at least this would mean that the MONGODB_URI constant is undefined, but I can't figure out why. It might be I am missing a package (I believe it's called) or that it's a problem with me running this code on windows, or something entirely different. Have also tried to google, but either I don't understand the answer or I can't find an answer.


Solution

  • From Node JS Documentation on Process

    The process.env property returns an object containing the user environment.

    Read this article on process.env for better understanding. I'm going to quote from the article about what is process.env for TL;DR purpose

    The process.env global variable is injected by the Node at runtime for your application to use and it represents the state of the system environment your application is in when it starts. For example, if the system has a PATH variable set, this will be made accessible to you through process.env.PATH which you can use to check where binaries are located and make external calls to them if required.

    That being said the problem you are facing is that your MONGODB_URI variable is undefined as your error says because you never defined it. The reason the article you followed did this is because the writer is deploying it to HEROKU and it will automatically run there. So, to solve your issue (if u want to run ur app locally)

    1) Download and Install MongoDB (If u haven't already).

    2) In your Package.JSON specifically in "start": "node index.js". You can update start script to "start": "MONGODB_URI=http://localhost:27017 node index.js" (From Fruty's answer). (Mongo local Server starts on PORT 27017 by default). This will first set Mongo_URI to local instance of ur Mongo in your system. Then run the Index.js file