How to check mongo database is connected? - node.js

I have mongodb up and running for the application how can i make sure when application start it is connected with db ?
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
var db = require('./config/db');
var port = process.env.PORT || 8080;
mongoose.connect(db.url);
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app); // configure our routes
app.listen(port);
console.log('listening on port ' + port);
exports = module.exports = app;
config > db.js
module.exports = {
url : 'mongodb://localhost/test-dev'
}

Related

Node App is running in server but not working when trying in browser

I have small node app that is doing some operations with the database, it is working fine locally but when i try to run it in the cloud server it is showing as running but unable to see anything on browser
I am using express framework and the server is running in centOS.
I tried many solutions but nothing is working
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var cors = require('cors');
const http = require('http');
const routes1 = require('./routes/routes');
// initialize our express app
const app = express();
// const mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect('<My mlab details>');
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var publicDir = require('path').join(__dirname,'/uploads/images/products');
app.use(express.static(publicDir));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors())
app.use('/api/routes', routes1);
let port = 80;
const server = http.createServer(app);
server.listen(port)
app.listen(port, () => {
console.log('Server is up and running on port numner ' + port);
});
I am expecting the port to listen properly and store in the mlab server
from your code it looks like you are using express
here you are initialling express
const app = express();
just attach listner to app
remove this two line of code
const server = http.createServer(app);
server.listen(port)
and use port like this
let port = process.env.PORT || 8000;
it will solve your problem
this is working code
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var cors = require('cors');
const http = require('http');
const routes1 = require('./routes/routes');
// initialize our express app
const app = express();
// const mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect('<My mlab details>');
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection
error:'));
var publicDir =
require('path').join(__dirname,'/uploads/images/products');
app.use(express.static(publicDir));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors())
app.use('/api/routes', routes1);
let port = process.env.PORT || 8000;
app.listen(port, () => {
console.log('Server is up and running on port numner ' + port);
});

NodeJs route not working

I am new to NodeJs. I am getting error with below code.
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
port = process.env.PORT || 9090,
mongoose = require('mongoose'),
Cheque = require('./models/cheque'),
router = express.Router();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
mongoose.connect('http://localhost:27017/utils/chequeman');
router.route('/cheques').post(function (req, res) {
console.log('u r in cheques.');
var cheque = new Cheque();
cheque.chequeReceiptDate = req.body.chequeReceiptDate;
cheque.save(function (err) {
if (err)
res.send(err)
res.json({ message: 'Cheque details added' });
});
});
app.use('/api', router);
app.listen(port);
console.log('Magin happens at' + port);
When I am trying POST request in postman I am getting response as "Cannot POST /api/cheques"
Please help.
Try to declare the variables that you are using.
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let port = process.env.PORT || 9090;
let mongoose = require('mongoose');
let Cheque = require('./models/cheque');
let router = express.Router();
Take your API static
app.use('/CHEQUEDIRECTORY', express.static(__dirname + '/CHEQUEDIRECTORY'))
Don't forget to export modules on you API.
Have you installed the packages correctly?

Error connecting to MongoDB: connect ECONNREFUSED 127.0.0.1:27017

I try to connect to MongoDB, but I get the error. Here is my code and the error below.
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var port = process.env.PORT || 8080;
var database = require('./config/database');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
mongoose.connect(database.localUrl);
app.use(express.static('./public'));
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'}));
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse
application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-
HTTP-Method-Override header in the request
require('./app/routes.js')(app);
app.listen(port);
console.log("App listening on port " + port);
Heres the error image

Package express-ws doesn't let clients connect

I have an express router defined for express-ws npm package. The router looks is exported like:
//ws.js
var express = require('express');
var router = express.Router();
var connections = {};
router.ws('/connect/', function (ws, req) {
// console.log(ws);
ws.on('close', function(x, y, z) {
console.log(a, b, c);
});
});
module.exports = router;
The (not all) statements in the express app are (and in order):
//app.js
var app = express();
var expressWs = require('express-ws')(app);
var index = require('./routes/index');
var ws = require('./routes/ws');
...
...
app.use('/ws', ws);
app.use('/*', index);
The server has statements like:
//bin/www - Generated by express generator
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
After I run it, I am not able to connect to /ws route over websocket. Am I missing something here? Is there a better way to create websocket running on Express 4?
This is the error I see at the client! What am I doing wrong?
changes to app.js
var app = express();
var server = require('http').Server(app);
var expressWs = require('express-ws')(app,server);
...
...
//module.exports = app;
module.exports = {app: app,server: server};
changes to bin/www
//var app = require('../app');
var app = require('../app').app;
...
...
//var server = http.createServer(app);
var server = require('../app').server;
I know this is old but here's the issue. HTTP server isn't required.
//app.js
const express = require('express');
const { app } = require('express-ws')(express());
const index = require('./routes/index');
const ws = require('./routes/ws');
...
app.use('/ws', ws);
app.use('/*', index);
...
app.listen(8080, () => console.log('Listening on port: 8080');

NodeJS Require, where do I use this?

Node JS require for the bittrex api... exactly where do it.
npm everything is installed including require...
var bittrex = require('bittrex-api');
on any page gives require is not defined
1) I'm using ui-router, server.js is not needed... I added one anyway.
var express = require('express');
var path = require('path');
//var logger = require('morgan');
//var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
//var bcrypt = require('bcryptjs');
var app = express();
app.set('port', process.env.PORT || 8080);
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/')));
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
now I want to add the bittrex ticker on the dashboard... so on the dashboard view I add
var market = 'BTC-LTC';
var bittrex = require('bittrex-api');
I turn on the server.js file and I get the require undefined message, I turn it off same message.
What am I doing wrong?

Resources