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(...);
);
Related
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"
I have this code that is being used by my app to do some basic CRUD and all the CRUD code resides in customers.js
I would like to have another file media.js that provides functionality to upload files and play multimedia.
How would i modify my routes to take care of the new file media.js.
This is my code
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
//load customers route
var customers = require('./routes/customers');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
// all environments
app.set('port', process.env.PORT || 4300);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
/*------------------------------------------
connection peer, register as middleware
type koneksi : single,pool and request
-------------------------------------------*/
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
port : 3306, //port mysql
database:'nodejs'
},'request')
);//route index, hello world
app.get('/', routes.index);//route customer list
app.get('/customers', customers.list);//route add customer, get n post
app.get('/customers/add', customers.add);
app.post('/customers/add', customers.save);//route delete customer
app.get('/customers/delete/:id', customers.delete_customer);//edit customer route , get n post
app.get('/customers/edit/:id', customers.edit);
app.post('/customers/edit/:id',customers.save_edit);
app.use(app.router);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
I'm not sure if you have ./routes/customers/index.js or ./routes/customers.js.
//load customers route
var customers = require('./routes/customers');
//load media route
var media = require('./routes/media.js');
...
app.get('/media/add', media.add); // You'd need a function defined and exported in your media.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,
...
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.
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 .