我在连接到我的mongohq数据库时遇到了重大问题。我正在按照本教程,但用远程mongoHQ db替换本地mongo DB:http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/
wines.js
var mongo = require('mongodb');
Db = mongo.Db;
BSON = mongo.BSONPure;
con = null;
server = new Server('troup.mongohq.com', 'mongo_port', {auto_reconnect: true});
DBCon = new Db('dev', server, {safe: false});
DBCon.open(function(err, db) {
if(!err) {
db.authenticate('username', 'password', function(err){
if(!err) con = db;
})
}
})
// exports.findById = function(req, res) {
// var id = req.params.id;
// console.log('Retrieving wine: ' + id);
// db.collection('wines', function(err, collection) {
// collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
// res.send(item);
// });
// });
// };
server.js
var express = require('express'),
path = require('path'),
http = require('http'),
wine = require('./routes/wines');
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser()),
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.post('/wines', wine.addWine);
app.put('/wines/:id', wine.updateWine);
app.delete('/wines/:id', wine.deleteWine);
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
尝试启动节点时出现错误:
/Sites/nodecellar/routes/wines.js:31
db.open(function(err, db) {
^
ReferenceError: db is not defined
at Object.<anonymous> (/Sites/nodecellar/routes/wines.js:31:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Sites/nodecellar/server.js:4:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
关于这里有什么问题的任何建议?
答案 0 :(得分:0)
您的问题几乎可以肯定是服务器连接设置。本教程提前更新了驱动程序,使所有平台上的接口统一,并且可接受的方法是使用MongoClient类进行设置。
请查看有关URL连接格式的说明,因为您可能需要传递凭据和数据库以连接到那里。