MegaRacer MegaRacer - 2 months ago 12
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');
mongoose.connect('mongodb://node:node@jello.modulusmongo.net:27017/hygeBe9b');

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

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 !');

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


router.route('/songs')
.post(function(req, res){
var song = new Song();
song.name = req.body.title;

song.save(function(err) {
if (err) { res.send(err);}
res.json({message : 'Song Created'});
})
})
var Song = require('./models/songs');


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

app.listen(port);
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"


The https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

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

Answer

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:

mongoose.connect('mongodb://[user]:[pass]@[hostAddress]:[port]/[databaseName]',callbackFunc)

for localhost

mongoose.connect('mongodb://localhost/databaseName',callbackFunc)

N.B: Ensure first your mongod is running