Node.js - Connecting to MongoDB using MongoHQ on Heroku

北战南征 提交于 2019-12-05 02:04:11

问题


I have a Node.js app using Express that stores data in a mongoDB (locally).

It's now pushed to heroku successfully on a cedar stack and the server is running. I added the mongohq addon through the terminal.

Now... how do I connect that mongoDB through mongohq to my application to start using it??? I don't see a tutorial for this anywhere online. If you can point me to one or get me started on where to add the configuration, I would greatly appreciate!

Thanks much.

Update:

I've tried the following (with real values for MYPASSWORD and MYDBNUMBER:

in routes.js

var db = mongoose.connect('mongodb://heroku:<MYPASSWORD>@staff.mongohq.com:10049/<MYDBNUMBER>');

in my schema.js (also tried using the heroku

var mongoose = require('mongoose');
mongoose.connect('mongodb://heroku:<MYPASSWORD>@staff.mongohq.com:10049/<MYDBNUMBER>');

my package.json

{
"name": "NAME"
, "version": "0.0.1"
, "dependencies": {
  "express": "2.4.6"
, "connect": "1.7.1"
, "stylus": ">= 0.0.1"
, "mongodb": ">= 0.9.6-7"
, "mongoose": ">= 2.0.0"
, "ejs": ">=0.4.3"
}
}

Right now, only the root '/' GET is successful. Actually, if I try /page/ANYTHING I can successfully get a rendered 500 Error page that I made to handle attempts to get 'pages' that haven't been created... That seems kind of weird to me. Everything else gives me an Internal Server Error.

ALSO, if i go to mongohq and open my database there, a collection for my model pages has been created and the indexes for uniqueness have been created, even tho I haven't been able to access the pages to create or view the model in my app...

happy to provide any other info... so stuck.


回答1:


We are using heroku against MongoHQ but in our case we created the MongoHQ account on our own so our solution is a bit different. Now, we are using the Redis plugin and in that case we connect to Redis using the heroku env variables. When you create a new plugin, Heroku adds a bunch of env variables that you can access from your node.js app easily doing this:

process.env.NAME_OF_VAR

In the case of Redis to go the name of the var is REDISTOGO_URL so our code looks like

process.env.REDISTOGO_URL

For MongoHQ the env variable seems to be MONGOHQ_URL

You may need to do some parsing. Heroku have some documentation for Ruby here http://devcenter.heroku.com/articles/mongohq#using_the_mongo_ruby_driver that should help you to get it going.

With respect to where to do this in an express app. We are doing all the setup on app.js that is our entry point in the app.

Hope this helps.



来源:https://stackoverflow.com/questions/7575664/node-js-connecting-to-mongodb-using-mongohq-on-heroku

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!