无法使用mLab数据库连接我的nodejs应用程序

时间:2017-06-08 10:04:32

标签: javascript node.js mongodb express mlab

我尝试将其与mlab数据库连接但是它无法正常工作,经历了很多stackoverflow的答案并尝试了所有内容,但错误仍然存​​在,请帮忙。

var express = require('express');
var mongojs = require('mongojs');
var mongodb = require('mongodb');
// var db = mongojs('contactlist',['contactlist']);
var uri = 'mongodb://user:pass@####.mlab.com:13702/contactlist'
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, contactlist) {

});

var db = mongodb.connect(uri);
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/contactlist', function(req, res){
    console.log("I received a GET request");
    db.contactlist.find(function(err, docs){
        console.log(docs);
        res.json(docs);
    });
});



app.post('/contactlist', function(req, res) {
    console.log(req.body);
    db.contactlist.insert(req.body,function(err,doc) {
        res.json(doc);
    });
});
app.listen(process.env.PORT ||3000, function(){
  console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});

我尝试在浏览器上插入数据后出现这些错误,甚至没有显示数据库中的数据。 错误:

TypeError: Cannot read property 'find' of undefined
        at D:\contactlistapp\server.js:17:16
        at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
        at next (D:\contactlistapp\node_modules\express\lib\router\route.js:137:13)
        at Route.dispatch (D:\contactlistapp\node_modules\express\lib\router\route.js:112:3)
        at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
        at D:\contactlistapp\node_modules\express\lib\router\index.js:281:22
        at Function.process_params (D:\contactlistapp\node_modules\express\lib\router\index.js:335:12)
        at next (D:\contactlistapp\node_modules\express\lib\router\index.js:275:10)
        at jsonParser (D:\contactlistapp\node_modules\body-parser\lib\types\json.js:103:7)
        at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
    { name: 'kkm', email: 'kmk' }
    TypeError: Cannot read property 'insert' of undefined
        at D:\contactlistapp\server.js:27:16
        at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
        at next 

1 个答案:

答案 0 :(得分:1)

MongoShell支持

db.[collection_name]语法(即属性上的集合名称),但在节点环境中,您必须使用以下语法: db.collection("collection_name").find()。与插入相同。

另请注意,MongoClient的连接功能是异步的。您必须从您指定的回调中获取对数据库的引用。

mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, contactlist) {
     db = contactlist;
});