Page hangs while doing operation on MongoDb database - node.js

I am using Cloude 9 environment for developing my nodejs app. In that I have written code to connect to mongodb database. I am successfully connecting to database. But when I try to do operations on database the page becomes not responsive and hangs.
Below is the code of my server.js file
var Db = require('mongodb').Db;
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var ejs = require('ejs');
var app = express();
var helpers = require('express-helpers')
var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var db;
helpers(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () {
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// MongoDB Connection
app.use(function(req, res, next) {
next();
})
app.post('/ajax-mongo-connect', function (req, res) {
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
if(err){
console.log(err);
}else{
var db = mongoClient.db("mydb");
console.log('database connected',db);
mongoClient.close();
}
})
})
Note that from my view page I am calling action ajax-mongo-connect with POST method. To call goes to app.post('/ajax-mongo-connect'... but page becomes irresponsible and hangs.
Let me know what I am doing.

You need to return something in your /ajax-mongo-connect route, for example res.send('its working dude!'); or call the next() function.
Cheers!

Related

Cannot get Express to find routes

I am working on making adjustments to teammates code and I haven't been able to understand how they have done their routing. I am attempting to have Express run a middleware script when an end-user goes to a new session of the web application.
I don't know what to test next to figure out how they have done their routing.
Main.js
// Dependencies
var http = require('http');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var busboy = require('connect-busboy');
var cors = require('cors');
var mongoose = require('mongoose');
// Configuration
var config = require('./config');
var twilio = require('twilio');
// Database
mongoose.connect(config.database);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
console.log('Connected to database');
});
var app = express();
app.set('port', process.env.PORT || 3000);
// Setup middleware
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.sessionSecret));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(busboy());
app.use(cors({
origin: true,
credentials: true
}));
app.all('/*',function(req,res){
twilio.notifyOnSession();
console.log('Message Sent');
})
var server = http.createServer(app);
var port = app.get('port');
server.listen(port);
console.log('Listening on port ' + port);
// Load server router
require('./router')(app);
/router/index.js
var path = require('path');
module.exports = function(app){
console.log('Initializing server routing');
require('./auth')(app);
require('./api')(app);
// Determine if incoming request is a static asset
var isStaticReq = function(req){
return ['/auth', '/api', '/js', '/css'].some(function(whitelist){
return req.url.substr(0, whitelist.length) === whitelist;
});
};
// Single page app routing
app.use(function(req, res, next){
if (isStaticReq(req)){
return next();
}
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
};
Your app.all('/*' is swallowing all requests before they can hit your router.
Don't do that.
I was able to resolve the issue by creating a new route with twilio.js and having the router look for the url twilio/new. Thanks all for the help.

i am getting this error "No default engine was specified and no extension was provided." in node.js when trying to send data into database

var express = require("express");
var app = express();
var path = require("path");
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydatabase"
});
app.get('/',function(req,res)
{
res.sendFile(path.join(__dirname+'/app.html'));
});
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'js');
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req,res)
{
res.render('index');
});//inserting data
app.post('/insert', function(req,res)
{
pool.getConnection(function(error,conn)
{
var queryString = "insert into customers(firstName,lastName)values('"+req.body.fname+"','"+req.body.lname+"')";
conn.query(queryString,function(error,results)
{
if(error)
{
throw error;
}
else
{
res.send('Inserted Successfully!')
}
});
conn.release();
});
});//server starting
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
app.listen(2000);
console.log("Running at Port 2000")
});
I am making a web page in which I want to insert data by the user so I have created this code in node.js to perform data tranfer but it is showing
No default engine was specified and no extension was provided.
What could be the problem?
i got my mistake its in app.set('view engine', 'js');
it should be app.set('view engine', 'ejs');
but when i fixed it a new error has arrived and that is
Failed to lookup view "index" in views directory "D:\nodejs/views"

Mongodb db.get('usercollection') not working corretly

Issue is that db is not working properly
app.js
var express = require('express');
var path = require('path');
var http = require('http');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
var routes = require('./routes');
var users = require('./routes/users');
var app = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.use(function(req,res,next){
req.db = db;
next();
});
routes/index.js
exports.index = function(req, res){
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
};
When I run userlist I get an error on line db.get('usercollection'). When I log req.db it is undefined.
How to resolve it?
you can directly use your db module in the index.js file
module.exports = (function() {
'use strict';
var apiRoutes = express.Router();
var Server = mongo.Server;
var Db = mongo.Db;
var BSON = mongo.BSONPure;
function connexionDataBase(callback){
var server = new Server('your db URL', 27017, {auto_reconnect: true});
db = new Db('you Db', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'you Db' database");
callback(err,db);
}
else{
console.log("not Connected to 'you Db' database");
callback(err,db);
}
});
})();
and in your app.js your can redirect the app routes to index.js :
var express = require('express');
var index = require('./index');
var app = express();
app.use('/index',index);

Cannot read property 'insert' of undefined

This is my first Node.js program using the Mongo db. This is my code:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var mongo = require("./routes/mongo");
var session = require('express-session');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var monStore=require("connect-mongo")(session);
var url = 'mongodb://localhost:27017/session';
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 4000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
app.post('/signup',function(req,res){
var email=req.param("email");
var fname=req.param("firstname");
var lname=req.param("lastname");
var password=req.param("password");
var url1="mongodb://localhost:27017/signup";
mongo.connect(url1, function(){
var db= mongo.collection('user');
db.user.insert({"username": email,
"password":password,
"firstname":fname,
"lastname":lname});
res.render("login",{title:"welcome"});
});
});
app.post('/login',function(req,res){
var email=req.param("email");
var password=req.param("password");
var url1="mongodb://localhost:27017/login";;
mongo.connect(url1, function(){
var db= mongo.collection('signup');
db.findOne({username: email, password:password}, function(err,user){
console.log(user.email);
if(user)
{
res.render("welcome");
}
else
{
res.render("login",{title:"ivalid"});
}
});
});
});
MongoClient.connect(url, function() {
console.log("Connected correctly to server.");
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
i get the error Cannot read property 'insert' of undefined where i am trying to insert values into the database. Am I missing some point here? Can somebody Please help me out?
You are using db variable as a reference to the collection:
var db= mongo.collection('user');
db.user.insert({"username": email,
...
The collection has no attribute called user, so that calling insert on it results in your error.
I believe that you wanted to do this:
var userCollection = var db= mongo.collection('user');
userCollection.insert({"username": email,
...

Accessing >=2 collections from the same db connection using Mongo-lite results in error

I am trying to access more than a single mongo collection from the same db connection using mongo-lite. Here is a sample express app.
var express = require('express') ;
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1','col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
db.collection('col1').insert({hi:5},function(){});
db.collection('col2').insert({hi:5},function(){});
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});
Here is the error I am getting on doing a GET on /:
Error: A Server or ReplSetServers instance cannot be shared across multiple Db instances
However if I use the following code the GET inserts the documents as expected
var express = require('express') ;
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1']);
db2 = mongolite.connect("mongodb://localhost/fnard", ['col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
db.collection('col1').insert({hi:5},function(){});
db2.collection('col2').insert({hi:5},function(){});
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
Do I need to really create a new connection for each collection I want to access?
The mongo-lite docs seem to suggest that this isn't the case - the .connect() option lets you specify which collections you want to use but it doesn't seem to work.
mongo-lite docs link
A race condition is giving you the error. The following works for me:
var express = require('express');
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1','col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
db.collection('col1').insert({hi:5},function(){
db.collection('col2').insert({hi:5},function(){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
});
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});
You need to nest your callbacks. Or, you can use a library like async:
var express = require('express');
var async = require( 'async' );
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1','col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
async.series( [
// First insert
function ( callback ) {
db.collection('col1').insert({hi:5},callback);
},
// Second insert
function ( callback ) {
db.collection('col2').insert({hi:5},callback);
}
// Send response
], function ( error, results ) {
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
} );
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});

Resources