Cannot read property 'insert' of undefined - node.js

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,
...

Related

Page hangs while doing operation on MongoDb database

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!

mongoose and node error : Cannot call method 'model' of undefined

I tried following a tutorial on mongoose/mongodb with node and have fallen into issues trying to get express/node to res.send json documents from the collection.
The following code is producing errors when I try to access localhost:3000/mongodb
The database and collection exist. The collection has 3 documents.
app.js
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = module.exports = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.engine('html', require('hogan-express'));
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')));
mongoose.connect('mongodb://localhost/xkayak');
var schema = new mongoose.Schema({ username: 'string', email: 'string', password: 'string'});
var usercollection = mongoose.model('usercollection', schema);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
require('./routes/index.js');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
index.js --the routes file
var app = require('../app.js');
app.get('/mongodb', function(req, res) {
app.mongoose.model('usercollection').find(function(err, usercollection) {
res.send(usercollection);
});
});
The error produced is:
500 TypeError: Cannot call method 'model' of undefined
What is wrong with my code? Did I set up the collection incorrectly? If I remove this code everything else works.
In your route, you are importing app. The problem is here:
var app = module.exports = express();
This means that when you import app.js you're going to get an instance of express, and not mongoose like you think when you do app.mongoose.model....
Consider:
app.js:
var app = express();
exports.express = app;
...
var mongoose = mongo.connect(...);
exports.mongoose = mongoose;
index.js:
app.express.get( ...
app.mongoose.model(...);
);

Express: unable to access POST data and set cookie at the same time

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.

Error while compiling WebStorm Node.js project

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 .

Node.js and Native MongoDB Connection fails

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.

Resources