0

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

5
  • can you telnet to with command : telnet 127.0.0.1 17027 ? Commented Jun 3, 2016 at 7:27
  • Nop @ThanhNguyenVan , i am using mac Commented Jun 3, 2016 at 7:27
  • Just curious if you started your mongod service? I have this ECONNREFUSED error always when i forgot to turn on. or can you restart your mongo service? You can also open a terminal, simply run mongo and see if you're able to connect Commented Jun 3, 2016 at 7:28
  • @ChinKang writing only mongo gives me no command found. I am using moongose Commented Jun 3, 2016 at 7:30
  • moongose is the JS connector to the mongoDB. mongo is the CLI comes together with the installation of MongoDB, so you should be able to run it on mac if you have mongo installed Commented Jun 3, 2016 at 7:33

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

ok thanks that worked, i hadn't specifically installed mongodb, i thought moongose does that. Thanks
0

Try calling the connection to mongo before app.listen, mongoose open a pool of connections by default for attend the requests

mongoose.connect('mongodb://localhost/dbname', function(err) {
    if (err) throw err;
    app.listen(port);
    console.log("Listening to PORT " + port);
});

Comments

0

Most common troubleshooting steps:

  1. Configured localhost incorrectly somewhere, so try changing your connection string to mongodb://localhost:27017/smartRideDb.
  2. Check if mongod is running at that port.
  3. Check if some other process is using that port.

3 Comments

how to check if mongod is running at that port and if not how to run it?
@MuhammadUmar Open your terminal and type mongo. See what happens
Just go to your terminal and type mongo. By default it uses that port, so if it goes to the mongo shell then you know mongod is running. Otherwise you can use ps -ef | grep mongo to check it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.