从Localhost MongoDB切换到使用MongoLab在Heroku上部署

时间:2015-03-02 21:48:19

标签: mongodb heroku deployment localhost

我使用MongoDB在我的本地计算机上构建应用程序,这在本地完全正常工作。但是一旦我将它部署到Heroku,我就无法连接到数据库或从REST服务中检索任何内容。我很多时候都会阅读文档并注意到他们需要在许多地方进行更新,这些都会让我失望。这是我的初始化代码:

非常感谢任何帮助或建议。

"use strict";

var express = require("express");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");

var server = express();
server.set("port", (process.env.PORT || 5000));
server.use(express.static(__dirname + "/public"));

server.listen(server.get("port"), function() {
  console.log("Node server is running at localhost:" + server.get("port"));
});


var router = express.Router();
/* GET home page. */
router.get("public", function(req, res) {
    res.render("index", { title: "MyApp" });
});

module.exports = router;

// **** LocalDB: "mongodb://localhost:27017/myapp"   ****
var mongo = require("mongoskin");
var db = mongo.db("mongodb://xxxxxx:xxxxxx@ds045511.mongolab.com:45511/xxxxxx", {native_parser:true});

var routes = require("./routes/index");
var users = require("./routes/users");
var divesites = require("./routes/myCollection");

var app = express();


// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + "/public/favicon.ico"));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, "public")));

// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
});

app.use("/", routes);
app.use("/users", users);
app.use("/myCollection", myCollection);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error("Not Found");
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get("env") === "development") {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render("error", {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render("error", {
        message: err.message,
        error: {}
    });
});


module.exports = app;

1 个答案:

答案 0 :(得分:0)

您可以使用环境变量process.env.MONGOLAB_URI代替,看看情况如何:

var mongo = require("mongoskin");
var db = mongo.db(process.env.MONGOLAB_URI, {native_parser:true});