Muhammad Umar Muhammad Umar - 6 months ago 53
Node.js Question

Node.js script not getting connected to Mongodb database in localhost

I have following test code to run mongodb along with node.js while creating rest api

MONGO.JS

var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/smartRideDb');
// create instance of Schema
var mongoSchema = mongoose.Schema;
// create schema
var userSchema = {
"id" : String,
"email" : String,
"password" : String
};
// create model if not exists.
module.exports = mongoose.model('user',userSchema);


index.js is defined as

var mongoOp = require("./models/mongo");
var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var router = express.Router();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));

app.use('/' , router);
var port = process.env.PORT || 3000;

/**
*
*
*
*/
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code)
{
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}

/**
*
*
*
*/
router.get("/",function(req,res)
{
res.json({"error" : false,"message" : "Hello World"});
});


//route() will allow you to use same path for different HTTP operation.
//So if you have same URL but with different HTTP OP such as POST,GET etc
//Then use route() to remove redundant code.

router.route("/users").get(function(req, res)
{
var response = {};
mongoOp.find({},function(err,data)
{
if(err)
{
response = {"error" : true,"message" : "Error fetching data"};
}
else
{
response = {"error" : false,"message" : data};
}

res.json(response);
});
});


app.listen(port);
console.log("Listening to PORT " + port);


When i run i get this error

Muhammads-MBP:Api Umar$ node index.js
Listening to PORT 3000

/Users/Umar/Desktop/Projects On List Data/Creative Studios/School Ride/Api/node_modules/mongodb/lib/server.js:242
process.nextTick(function() { throw err; })
^
Error: connect ECONNREFUSED 127.0.0.1:27017
at Object.exports._errnoException (util.js:890:11)
at exports._exceptionWithHostPort (util.js:913:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1057:14)


Why is mongodb not gett

Answer

You may want to try to ensure the MongoDB has properly setup first by following

  1. MongoDB is installed successfully (OSX guide here)
  2. Run mongod in terminal after installed to run the MongoDB
  3. Run mongo in another terminal, and you should be able to see something similar.

.

MongoDB shell version: 3.2.4
connecting to: test