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);
Related
I want to get the number of documents in the 'image' collection.
my code is
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname+'/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
dburl = "mongodb+srv://...";
mongoose.connect(dburl);
var db = mongoose.connection;
//...
var imageSchema = mongoose.Schema({
image_name:{type:String, required:true, unique:true}
});
var Image = mongoose.model('image', imageSchema);
var Dcount = db.image.countDocuments({});
but the console :
enter image description here
countDocuments() is available directly on model
You should be doing Image.countDocuments()
Image.countDocuments({}, function (err, count) {
if (err){
console.log(err)
}else{
console.log("Count :", count)
}
});
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 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'
}
Socket.io can be used in the general html page, but it can not be used in the mustache page?
For example:
app.js
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'mustache'); // name your templates
app.engine('mustache', require('hogan-middleware').__express);
var routes = require('./routes/index');
app.use('/', routes);
routes\index.js
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
var request = require('request');
var serialport = require('serialport');
var Serialport = serialport;
router.get('/machine_mode', function(req, res, next) {
res.render('machine_mode', { title: 'test' });
});
io.sockets.on('connection',function(socket){
var str='hello';
io.sockets.emit('view',str);
});
views\test.mustache
<body>
</body>
<script src="/js/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
socket.on('str',function(data){
})
});
the test page error:
can not GET
http://localhost:8001/socket.io/socket.io.js
app.js
var express = require('express');
var router = express.Router();
var app = express(); // Brackets Missing
var server = require('http').createServer(app); // Need to do like this
var io = require('socket.io').(server); // Need to pass server
var request = require('request');
var serialport = require('serialport');
var Serialport = serialport;
router.get('/machine_mode', function(req, res, next) {
res.render('machine_mode', { title: 'test' });
});
io.on('connection',function(socket){ // io.socket is not required
var str='hello';
sockets.emit('view',str);
});
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!