Thursday 8 June 2017

Can't connect my nodejs application with mLab database

I tried connecting it with mlab database but its not working, went through a lot of stackoverflow answers and tried everything but the errors are still there, please help.

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);
});

I am getting these errors after I try inserting data on the browser, its not even displaying the data from the database. Errors:

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 



via Shreya Shah

No comments:

Post a Comment