While conencting mongoDb with application facing issue : "UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017"
Tried Solutions :
- Reinstalling mongoDb
- Restarting the mongoDb service from control panel services.
Code :
var express = require('express');
var app = new express();
var bodyParser = require('body-parser')
var mongoose = require('mongoose')
var user = require('./model/user')
const hostname = '127.0.0.1';
const port = 3000;
var router = express.Router();
mongoose.connect('mongodb://localhost:27017/userdb', { useNewUrlParser: true });
var users = [{ name: "Jane", age: 20 }, { name: "Mark", age: 40 }, { name: "Janefer", age: 40 }]
app.use(bodyParser.urlencoded({ extended: true }))//converts it into obj
router.route('/users')
.get((req, res) => {
//fetch record from users collectiobn
user.find({}, (err, users) => {
if (err) {
res.json({ msg: 'error in fetching data from DB' })
}
else {
res.json(users)
}
})
// res.json(users)
})
.post((req, res) => {
})
app.use('/api', router)//middleware to direct all req
app.listen(port, hostname, () => {
console.log("Server listening on 3000")
})
Error screenshot :
CodePudding user response:
you can try to check which port mongodb is using in your mongodb.conf
after that if you still are have problem you can run the command ps aux | grep mongo
and post the result.
CodePudding user response:
Instead of [localhost] use [127.0.0.1]. like this - 'mongodb://127.0.0.1:27017/userdb'