Mongoose is undefined error - node.js

First time i have tried out to create a simple mean application.
I have followed the steps as per the below link
https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application#starting-our-node-application-packagejson
Finally i am getting the errors as
ReferenceError: mongoose is not defined
at Object.<anonymous> (C:\Users\Myname\Desktop\Mean sample\server.js:19:2)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
server.js
// modules =================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
// config files
var db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to our mongoDB database
// (uncomment after you enter in your own credentials in config/db.js)
mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('Magic happens on port ' + port);
// expose app
exports = module.exports = app;
How to fix it?
Can anyone please explain the steps to clear this issue

install mongoose
npm i mongoose --save
then import in your server.js file
var express = require('express');
var mongoose = require('mongoose') // import it
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

Related

Hello World Node.js/Express application error

I am learning MEAN stack so started with Node.js and Express first. I run Nginx on Windows 10. I installed the latest Node. NPM version is 3.10.3, Node version is 6.7.0, and Express version is 4.14.0. I did npm install express --save, npm install mongoose --save, npm install body-parser --save, and created the server.js file. I did node server on my sources and I got the following error:
C:\nginx\html>node server
C:\nginx\html\server.js:7
app.get('/', function(req, res){
^
TypeError: app.get is not a function
at Object. (C:\nginx\html\server.js:7:5)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
C:\nginx\html>
And the code in my server.js file is:
var express = require('express');
var express = require('mongoose');
var express = require('body-parser');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(80);
I am not sure how a hello world application can go wrong. I saw a lot of tuts and code with the same thing but working for them. Even the Express's official hello world app has same code.
try this
var express = require('express');
var mongoose= require('mongoose');
var bodyparser = require('body-parser');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(80);
You need to install express not expression as following
npm install express --save
and then you like play
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/', function(req, res){
res.send('hello world');
});
app.post('/', function(req, res){
res.json({data: req.body});
});
app.listen(3000);
and then try to listen another port that is above 1024 may be 3000 or 8080 or anything else otherwise you have to run cmd as Administrator

Socket.io and Express 3.2.6 : Object #<Server> has no method 'connect'

I see that many peoples have problem like mine but I don't find an answer.
I use Express 3.2.6 and I want to add Socket.io.
Server side :
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, index = require('./routes/index')
, http = require('http')
, path = require('path')
, nunjucks = require('nunjucks')
, mongoose = require('mongoose')
, validator = require('validator');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'nunjucks');
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 server = http.createServer(app);
var io = require('socket.io').listen(server);
var socket = io.connect();
I think that I make a lot of mistakes.
But I do not understant why node send me that :
var socket = io.connect();
^
TypeError: Object #<Server> has no method 'connect'
at Object.<anonymous> (C:\Users\Damien\workspace\project\app.js:35:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
UPDATE
I changed for express.io
http://express-io.org/
But I have a problem. I have no error message but my server and my client do
not seem to communicate.
Client part :
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script type="text/javascript">
document.onload = function(){
var socket = io.connect("http://127.0.0.1:8080");
//Emit ready event.
socket.emit('ready');
//Listen for the talk event.
socket.on('talk', function(data) {
console.log(data);
});
};
</script>
Server part :
var app = require('express.io')()
var nunjucks = require('nunjucks')
var mongoose = require('mongoose')
var validator = require('validator');
var routes = require('./routes')
var index = require('./routes/index')
app.http().io()
app.set('view engine', 'nunjucks');
app.set('views', __dirname + '/views');
mongoose.connect( '' );
nunjucks.configure('views', {
autoescape: true,
express: app
});
var urlSchema = new mongoose.Schema({
long : String,
count : Number
}
);
//create model
var urlModel = mongoose.model('urls', urlSchema);
app.get('/', index.index);
//Setup the ready route, and emit talk event.
app.io.route('ready', function(req) {
req.io.emit('talk', {
message: 'io event from an io route on the server'
})
})
app.listen(8080);
I do not understand who there is nothing in client console.
I found the problem :
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
Must be
<script src="/socket.io/socket.io.js"></script>

Unable to use express sessions in heroku nodejs app

In my app.js I have:
var express = require('express')
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var flash = require('connect-flash');
....
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser('3mKay'));
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.session({ secret: 'thisISmyS3cR3t'}));
This crashes with the following message in Heroku.
Error: Most middleware (like session) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
at Function.Object.defineProperty.get (/app/node_modules/express/lib/express.js:89:13)
at Object.<anonymous> (/app/app.js:25:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
I ran so it does exist in the package.json file as well:
npm install express-sessions --save
"dependencies": {
....
"express": "~4.8.6",
"express-session": "^1.8.1",
"passport": "^0.2.1",
"passport-local": "^1.0.0",
....
It works fine when I comment out the
app.use(express.session({ secret: 'thisISmyS3cR3t'}));
And I've also tried variations of the above but it gives the same error message. Any ideas what may be causing this to happen? Something I might have overlooked...
Once you install it, you have to actually use it in your code:
var express = require('express');
var session = require('express-session');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var flash = require('connect-flash');
....
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser('3mKay'));
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(session({ secret: 'thisISmyS3cR3t'}));

express - app `index.jade` not properly supplied by the `exports` function

I am trying to make a app, in the app directory this is my app.js file. in the app.js I am requiring the router folder and exporting the Routes. But I am not able to render the index.jade using the Router instead i am getting error:
D:\Projects\socialApp\node_modules\express\lib\router\index.js:423
throw new TypeError(msg);
^
TypeError: Router.use() requires callback function but got a [object Undefined]
at D:\Projects\socialApp\node_modules\express\lib\router\index.js:423:13
at Array.forEach (native)
at Function.use (D:\Projects\socialApp\node_modules\express\lib\router\index
.js:419:13)
at D:\Projects\socialApp\node_modules\express\lib\application.js:178:21
at Array.forEach (native)
at Function.use (D:\Projects\socialApp\node_modules\express\lib\application.
js:175:7)
at Object.<anonymous> (D:\Projects\socialApp\app.js:22:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
D:\Projects\socialApp>
here is my app.js:
var express = require("express"),
passport = require("passport"),
passportLocal = require("passport-local"),
bodyParser = require("body-parser"),
cookieParser = require("cookie-parser"),
expressSession = require("express-session"),
jade = require("jade"),
mongoose = require("mongoose"),
routes = require('./routes'),
port = process.env.PORT || 3000,
app = express();
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
var routes = require('./routes/index')(passport); //i am calling here
app.use('/', routes); // not getting index.jade on screen.
app.listen(port, function(){
console.log('Port Listing to ' + port + ":" + __dirname);
});
here is what in the router folder and in the index.js:
var express = require('express'),
router = express.Router();
module.exports = function(passport){
router.get('/', function(req,res){
res.render('index'); //i am not getting index.jade from view folder getting error
});
}
any one figure-out the issue please?
You need to return router; at the end of your module.exports function.

nodejs/express - cannot load routes using passport

I am trying to use passport to add user sessions on my webapp. I have configure my main js file as follow:
/**
* Module dependencies.
*/
var express = require('express');
var user = require('./server/routes/user');
var routes = require('./server/routes/index');
var http = require('http');
var path = require('path');
var app = express();
var passport = require('passport');
var flash = require('connect-flash');
require('./server/config/passport')(passport); // pass passport for configuration
// all environments
app.set('port', process.env.PORT || 3000);
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(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.configure(function(){
// required for passport
app.use(express.session({ secret: 'ilovesefounders' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
})
// routes ======================================================================
require('./server/routes/index')(app, passport); // load our routes and pass in our app and fully configured passport
routes.mount(app);
However when i try to launch it I get the following error:
require('./server/routes/index')(app, passport); // load our routes and pass i
^
TypeError: object is not a function
at Object.<anonymous> (/Path/app.js:38:33)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
What's going wrong here?
I don't know how your index.js looks like but you probably did not export your function module.
Check if index.js looks something like this:
module.exports = function(app, passport) {
/* code */
};
And you don't need to require "./server/routes/index" again.

Resources