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
telnet 127.0.0.1 17027?mongoand see if you're able to connectmongois the CLI comes together with the installation of MongoDB, so you should be able to run it on mac if you have mongo installed