The problem: web page works only if i manually start the mongodb. Otherwise i get error "Error failed to connect 127.0.0.1:27017". However, I believe i do create server, maybe i am missing some step.
Also, feel free to point out better ways of doing things, or if something is outdated...
The code:
var express = require('express'),
app = express(),
cons = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
var mongoclient = new MongoClient(new Server("127.0.0.1", 27017));
var db = mongoclient.db('course');
app.get('/', function(req, res){
// Find one document in our collection
db.collection('hello_combined').findOne({}, function(err, doc) {
if(err) throw err;
res.render('hello', doc);
});
});
app.get('*', function(req, res){
res.send('Page Not Found', 404);
});
mongoclient.open(function(err, mongoclient) {
if(err) throw err;
app.listen(8080);
console.log('Express server started on port 8080');
});
If you really need to start it "from nodejs", you can start mongodb when you start your node.js server using the child_process module.
Add the code below in your app code :
var child_process = require('child_process')
child_process.exec('start mongod', function (err, stdout, stderr) {
if (err) {
console.log(err);
return;
}
});