如何使用MongoHQ和Node.js在Heroku上设置MongoDB?

时间:2014-02-27 06:43:47

标签: javascript node.js mongodb heroku express

我有一个本地运行的应用程序,这就是我习惯的......

Heroku提供了以下代码段:

var mongo = require('mongodb');

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

mongo.Db.connect(mongoUri, function (err, db) {
  db.collection('mydocs', function(er, collection) {
    collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
    });
  });
});

这是MongoHQ的代码片段:

MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) {
  // operate on the collection named "test"
  var collection = db.collection('test')

这是MongoDB的Node.js / Express中的localHost代码:

var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;

var mongoclient = new MongoClient(new Server('localhost', 27017,
                                                { 'native_parser' : true }));
var db = mongoclient.db('demo');


mongoclient.open(function (err, mongoclient) {
    if (err) throw err
    app.listen(9999);
    console.log("Express server started on port 9999");
});

如何转换此代码集,或合并这两个代码集??

1 个答案:

答案 0 :(得分:0)

var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/demo';


var mongoclient = new MongoClient(new Server(mongoUri,
                                                { 'native_parser' : true }));

mongoclient.open(function (err, mongoclient) {
    if (err) throw err
    app.listen(9999);
    console.log("Express server started on port 9999");
});

试试。