Error while compiling WebStorm Node.js project - node.js

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 .

Related

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

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(...);
);

Using piler with express 3 and nodejs

I want to run Express 3.3.x with its default implementation.
Express uses its routes module, so what I have to do, if JS and CSS is accessible by any view in any route?
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var piler = require('piler');
var mongoose = require('mongoose');
var config = require('./config');
var app = exports.app = express();
var js = piler.createJSManager();
var css = piler.createCSSManager();
var srv = require('http').createServer(app);
// all environments
js.bind(app,srv);
css.bind(app,srv);
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(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
js.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
/**
* Routes
*/
var routes = require('./routes');
app.get('/', routes.index);
srv.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
In the example of piler:
app.get("/", function(req, res){
res.render("index.jade", {
layout: false,
js: js.renderTags(),
css: css.renderTags()
});
});
This works. But I have
app.get('/', routes.index);
So what I have to do, that js.renderTags() works in every view?
If you are trying to pass variables to render, you can use res.locals
app.use(function(req,res,next){
res.locals.layout= false;
res.locals.js= js.renderTags();
res.locals.css= css.renderTags();
next();
});
Use this before your router but don't overwrite your locals (res.locals={...})

backbone.js sending "OPTIONS" as a restful request

Backbone talking to node/express running locally os x 10.6.8. Trying to populate a clientside backbone model with fetch. Thinking I have fetch wrong. Most of app_stuff.js is cut-and-paste. Curious why node/express sees the request as OPTIONS instead of GET (or POST?) and if I have the terminology right. I think I can make it work like this but would rather pay the dues for some best practices while still an absolute newb.
backbone
(function($) {
var Stuff = Backbone.Model.extend({
});
var Collec = Backbone.Collection.extend({
model: Stuff,
url: 'http://localhost:3000/stuff'
});
var nstuff = new Collec;
nstuff.fetch(
{ data: $.param({ name: "helloworld"}) }
);
})(jQuery);
app_stuff.js
var express = require('express')
, routes = require('./routes')
, stuff = require('./routes/stuff')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
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')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/stuff', stuff.index);
app.options('/stuff', function() { console.log("stuffed"); });
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
terminal output
$ node timeline/app_stuff.js
Express server listening on port 3000
stuffed

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