0

我浏览了几篇 stackoverflow 文章并尝试了不同的连接方式,但它们都不起作用。到目前为止,我已经尝试过:

var mongodb = require('mongodb');
var uri = 'mongodb://Userxxx:Passxxx@ds0URI:PORT/heroku_appXXX';
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, db) {
});

崩溃并出现以下错误:

TypeError:无法调用未定义的方法“连接”

然后我尝试了这个:

mongo = require('mongodb')
Server = mongo.Server
Db = mongo.Db
BSON = mongo.BSONPure;
con = null;

server = new Server('xxxxx.mongolab.com', 'PORT', {auto_reconnect: true});
DBCon = new Db('xxxxx', server, {safe: false});
DBCon.open(function(err, db) {
    if(!err) {
          db.authenticate('xxxxx', 'xxxxx', function(err){
                  if(!err) con = db; 
                 })  
            }   
      }); 

这给了我一个错误:/app/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:10 number') throw "host and port must be specified [" + host + ":" + port + "]" ; 必须指定主机和端口

有谁知道这样做的正确方法?

4

1 回答 1

0

我在 Heroku 中使用过 MongoClient。该代码看起来与您所拥有的没有什么不同:

var MongoClient = require("mongodb").MongoClient;
MongoClient.connect(databaseString, function (err, result){
     if (err) {
     }
}

由于您遇到的错误(MongoClient 未定义),我想知道您的 package.json 文件是否正确。在我的测试中,它看起来像这样:

{
    "name": "test",
    "version": "0.0.1",
    "dependencies": {
        "express": "2.5.x", "mongodb": "1.2.14", "node-static": "0.7.0"
    },
    "engines": {
        "node": "0.8.x",
        "npm": "1.1.x"
    }
}
于 2013-09-13T05:24:53.743 回答