I am trying to set up a simple mongodb test server within my app.js node application but I keep getting "TypeError: Cannot read property 'arbiterOnly' of undefined". I am running it on local host and I have installed mongo db by running npm install mongodb in the folder I am making the application in. any help one what I am doing wrong would be greatly apreciated
here is my code for my application
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('test', new Server('localhost:', 3100, {}));
var insertData = function(err, collection) {
collection.insert({name: "Kristiono Setyadi"});
collection.insert({name: "Meghan Gill"});
collection.insert({name: "Spiderman"});
// you can add as many object as you want into the database
}
var removeData = function(err, collection) {
collection.remove({name: "Spiderman"});
}
var updateData = function(err, collection) {
collection.update({name: "Kristiono Setyadi"}, {name: "Kristiono Setyadi", sex: "Male"});
}
var listAllData = function(err, collection) {
collection.find().toArray(function(err, results) {
console.log(results);
});
}
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
client.open(function(err, pClient) {
client.collection('test_insert', insertData);
// client.collection('test_insert', removeData);
// etc.
});
var people = [{name:'Keth',age:'33',email:'ktater#gmail.com'},
{name:'Donny',age:'20',email:'donjuan86#hotmail.com'},
{name:'Loran',age:'26',email:'geegeenat#facebook.com'},
{name:'Max',age:'18',email:'axxanan#gmail.com'}];
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/people', function(req, res){
res.render('peeps', {people:people});
});
app.get('/people/:id', function(req, res){
var guy;
for (var i =0 ; i < people.length ; i++)
{
if(people[i].name == req.params.id)
guy = people[i];
}
res.render('viewPerson', {guy:guy});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
My first guess here is that the connection is not opening. Try logging err with console.log in the client.open function. Also, the post you're getting your test code from is about 18 months old, it's possible that the code is out of date.
Related
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,
...
I'm new to Node.js and Express.
How can I access the variable created in "app.js" called "pg" in "routes/index.js"?
app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var pg = require('pg');
var conString = "postgres://someuser:somepass#localhost/postgres"
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
routes/index.js
/*
* GET home page.
*/
exports.index = function(req, res){
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('SELECT NOW() AS "theTime"', function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].theTime);
//output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
client.end();
});
});
I got the error in the browser:
Express 500 ReferenceError: pg is not defined
Can you guys give me a clue?
Best Regards
A simple way of passing anything to route handlers (whether they are declared in different files or not) in Express is to use app.locals:
// app.js
...
var app = express();
...
app.locals.someVar = someValue;
...
// somewhere else
module.exports.myhandler = function(req, res) {
var someVar = req.app.locals.someVar;
...
};
// app.js
var routes = require('./routes/index')({ varname: thevar });
...
...
And
// /routes/index.js
module.exports = function(options) {
var moduleVar = options.varname;
return {
someMethod: function (req, res) { var i = moduleVar + 2; // etc},
anotherMethod: function (req, res) {}
};
};
I do this when I create a connection (or connection pool) and simply want my modules to have access to the db without having to create another connection. All depends on your project of course, one of my hit tracking modules uses it's own connection, so I pass it the db info and from there it does it's own thing. This allows me to have multiple apps using this tracker module while each connecting to their own db.
You could define the variable without the var keyword to make the variable global.
what I'm trying to achieve is to accept requests for a value, add that value to an array, run a function on it that'll query it and then remove it from the array with the shift function. What I have so far is a simplified framework of that, but it's now giving me this error.
RangeError: Maximum call stack size exceeded
if there's anything I can do to improve my code as well please let me know.
app.js
var express = require('express')
, http = require('http')
, path = require('path')
, fs = require('fs')
, eventEmitter = require('events').EventEmitter;
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
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')));
});
var ee = new eventEmitter;
var queries = new Array();
ee.on('next', next_search);
function next_search() {
console.log(queries);
search();
}
function search() {
// do something
queries.shift();
console.log(queries);
ee.emit('next')
}
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.post('/search', function(req, res) {
letter = req.param('letter');
console.log(letter);
queries.push(letter);
next_search();
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
jQuery code
$(document).ready(function() {
$('#letter').on("keyup", function() {
letter = $('#letter').val();
$.post("/search", { letter: letter}, function(data) {
$('#status').html(data);
});
});
});
This is an infinite function call, when you post. next_search -> search ->ee next event-> next_search -> ...
ee.on('next', next_search);
function next_search() {
console.log(queries);
search();
}
function search() {
// do something
queries.shift();
console.log(queries);
ee.emit('next') // execute first line
// only do this when queries is non-empty
}
You should check if queries is not empty, only then do next_search.
I'm writing an application that takes in a post request and sets a cookie pulled from the POST info. I'm stuck in a catch 22. In the first code sample I can set the cookie but can't access the data, in the second I can access the data but can't set the cookie. I'm sure I'm missing some basic concept of how the middle ware works but I can't for the life of me find the info I need.
The code below creates the cookie as expected but my post variable become undefined
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(function (req, res, next) {
var cookie = req.cookies.cokkieName;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
//cookie is set but I can't use req.post.xxxx. It"s always undefined
res.cookie("price", 111, { maxAge: 10000 });
console.log('cookie has been created successfully');
}
else
{
console.log('cookie exists', cookie);
}
next();
});
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', handshake.token);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The following code executes the setCookie callback (because the console output shows up), and on the console the variables are properly defined, but the cookie is not set.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
var setCookie = function (req, res, next) {
var cookie = req.cookies.cokkieName;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
res.cookie("price", 111, { maxAge: 10000 });
//in the console the post.body.xxxx data appears correctly but no cookie!!!
console.log('cookie has been created successfully',post.body.xxx);
}
else
{
console.log('cookie exists', cookie);
}
next();
};
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', setCookie ,handshake.token);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Trying to make the code more readable introduced too many typos that weren't relevant to my code. I took the suggestion and changed the code in the following way but it still doesn't write a cookie to the client.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, crypt = require('crypto')
, io = require('socket.io')
, db = require('levelup')('./mydb')
, path = require('path');
var app = express();
app.use(express.cookieParser());
app.use(express.bodyParser());
var cookieMiddleware = function (req, res, next) {
var cookie = req.cookies.user;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
// no: set a new cookie
var random = Math.random().toString();
random=random.substring(2,random.length);
sessionToken = Date.now() + random;
salt = sessionToken + req.body.address;
sha2 = crypt.createHash('sha256');
sha2.update(sessionToken);
var price = req.body.price;
var encryptedSession = sha2.digest('hex');
console.log('post body',price );
res.cookie('user','price' , { maxAge: 100000 });
console.log('existing cookies', req.cookies);
}
else
{
console.log('cookie exists', req.cookies);
}
next();
};
//development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.session({secret: "TheSuperSecretStringForHashing"}));
app.use(express.methodOverride());
app.use(app.router);
//app.use(express.favicon());
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', cookieMiddleware , handshake.token);
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
io = io.listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
The handshake.js handler
exports.token = function(req, res){
req.body.title = 'Payment Portal';
res.render('payment_init', req.body);
};
You are checking for a cookie named cokkieName, but the cookie you are setting has the name price.
Try changing this to:
var cookie = req.cookies.price;
cookie should now contain your cookie value.
I just created a simple project in WebStorm using Express module
then I install mongoose and after that I have tried to connect to MongoDB, but it's giving this exception:
Index.js
var mongoose = require('mongoose');
mongoose.connect('localhost', 'Test');
var schema = mongoose.Schema({ name: 'string' },{age:'int'});
var Human = mongoose.model('Human', schema);
exports.saveHuman = function (req,res){
"use strict";
var Ahs = new Human({name:'Dumy'},{age:24});
Ahs.save(function(error , data ){
if(error){
console.log("Not working");
}
else{
res.send(Ahs.name + "Created !");
}
});
};
exports.index = function(req, res){
"use strict";
res.render('index', { title: 'Express' });
};
app.js
var express, routes, user, http, path;
express = require('express');
routes = require('./routes');
user = require('./routes/user');
http = require('http');
path = require('path');
var app = express();
app.configure(function(){
"use strict";
app.set('port', process.env.PORT || 3000);
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(){
"use strict";
app.use(express.errorHandler());
});
app.get('/saveHuman',routes.saveHuman);
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
"use strict";
console.log("Express server listening on port " + app.get('port'));
});
Now, when I run the project it shows this in console .