简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM