MegaRacer MegaRacer - 10 months ago 40
Node.js Question

Database connection not working in Express

Hi I am following along an article and can't really get across a POST api.
I am using modulus for connecting to database uri.

Here's my code.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

var mongoose = require('mongoose');

app.use(bodyParser.urlencoded({extended : true}));

var port = process.env.port || 8080;

var router = express.Router();

//middleware to use for all requests

router.use(function(req, res, next){
console.log('Something is going on here !');

router.get('/', function(req, res){
message: "Welcome to first API coding !"

.post(function(req, res){
var song = new Song(); = req.body.title; {
if (err) { res.send(err);}
res.json({message : 'Song Created'});
var Song = require('./models/songs');

app.use('/api', router);

console.log('Server running on port: ' + port);

Model file

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var SongsSchema = new Schema({
title: String

module.exports = mongoose.model('Song', SongsSchema);

Here's my postman request code

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Cache-Control: no-cache" -H "Postman-Token: 5b280358-3de8-b52c-590b-430f5f4b6766" -d 'title=demo' "http://localhost:8080/api/songs"


And importantly how can I debug my code to see where the error lies ? API seems fine there.

Answer Source

can check this one and see what error shown in your console:

var db = mongoose.connect('mongodb://localhost/dbName', function(err) {
    if (err) {
        console.log('Could not connect to MongoDB!', err);

connection syntax:


for localhost


N.B: Ensure first your mongod is running