I am trying to wrap my head around defining and using an API in Express, using Mongoose to hook up with MongoDB. So far I am saving objects just fine form input on the front end. However, I seem to be lost when it comes down to retrieving and displaying the data I've saved.
Here is some code:
db.js:
const mongoose = require('mongoose');
//mongoose setup
mongoose.connect(mongooseUrl, { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('mongoose connected to ' + mongooseUrl);
});
module.exports = db;
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// import routers
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var apiRouter = require('./routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', apiRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
/routes/api.js:
var express = require('express');
var mongoose = require('mongoose');
var db = require('../config/db.js');
var Kitten = require('../models/kitten.js');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('api', {
title: 'Test API',
content: 'you\'re in the right place',
buttontext: 'send POST request'
});
});
router.post('/newKitten', function(req, res, next) {
var kitty = new Kitten({
name: req.body.name,
color: req.body.color
});
console.log("new kitty: " + kitty.name + " color: " + kitty.color );
kitty.save().then(console.log(kitty + " was saved to the database"));
res.send('new: ' + kitty);
});
router.get('/kittens', function (req, res, next) {
var kittens = Kitten.find({}, 'name color');
res.render('kittens', {title: 'Kittens', list_kittens: kittens });
});
module.exports = router;
models/kitten.js
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var kittenSchema = new Schema({
name: String,
color: String
});
var Kitten = mongoose.model("Kitten", kittenSchema);
module.exports = Kitten;
views/kitten.hbs:
<h1>{{title}}</h1>
<ul>
{{#each list_kittens as |kitten|}}
<li>name: {{kitten.name}}, color: {{kitten.color}}</li>
{{/each}}
</ul>
Now with all that laid out, when I visit http://localhost:3000/api/kittens this is what I see:
The kittens are stored in MongoDB, proof:
I have no idea why this is not rendering the kittens I have saved in my MongoDB database... The data is there, but I seem to be confused about how mongoose is supposed to be querying the data. Any and all help is appreciated. I've been stuck on this for a few days.
Model.find returns a promise. You have to add a function then to get the kittens and render them:
Kitten.find(...)
.then(kittens => {
res.render(...)
})
EDIT
Based on #Francisco Mateo comment, Kitten.find returns a Query you can execute with exec. Here is the code:
Kitten.find(...).exec()
.then(kittens => {
res.render(...)
})
In routes/api.js
var express = require('express');
var mongoose = require('mongoose');
var db = require('../config/db.js');
var Kitten = require('../models/kitten.js');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('api', {
title: 'Test API',
content: 'you\'re in the right place',
buttontext: 'send POST request'
});
});
router.post('/newKitten', function(req, res, next) {
var kitty = new Kitten({
name: req.body.name,
color: req.body.color
});
console.log("new kitty: " + kitty.name + " color: " + kitty.color );
kitty.save().then(console.log(kitty + " was saved to the database"));
res.send('new: ' + kitty);
});
router.get('/kittens', async function (req, res, next) { **//Change here**
var kittens = await Kitten.find({}, 'name color'); **//change here**
res.render('kittens', {title: 'Kittens', list_kittens: kittens });
});
module.exports = router;
The Kitten.find({}, 'name color') is returning a promise , so you have to wait until the data is returned.
Related
I want make auth app using nodejs and got error like the title :(
but code for app.js is already like this
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: '123456cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))
app.use(express.static(path.join(__dirname, 'public')));
var registrationRouter = require('./routes/registration-route').default;
var loginRouter = require('./routes/login-route').default;
var dashboardRouter = require('./routes/dashboard-route').default;
var logoutRouter = require('./routes/logout-route');
app.use('/', registrationRouter);
app.use('/', loginRouter);
app.use('/', dashboardRouter);
app.use('/', logoutRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(3000);
module.exports = app;
this is registration-route.js
var express = require('express');
var router = express.Router();
var db = require('../database');
// to display registration form
router.get('/register', function(req, res, next) {
res.render('registration-form');
});
// to store user input detail on post request
router.post('/register', function(req, res, next) {
inputData ={
username: req.body.username,
email_address: req.body.email_address,
password: req.body.password,
confirm_password: req.body.confirm_password
}
// check unique email address
var sql='SELECT * FROM registration WHERE email_address =?';
db.query(sql, [inputData.email_address] ,function (err, data, fields) {
if(err) throw err
if(data.length>1){
var msg = inputData.email_address+ "was already exist";
}else if(inputData.confirm_password != inputData.password){
var msg ="Password & Confirm Password is not Matched";
}else{
// save users data into database
var sql = 'INSERT INTO registration SET ?';
query(sql, inputData, function (err, data) {
if (err) throw err;
});
var msg ="Your are successfully registered";
}
res.render('registration-form',{alertMsg:msg});
})
});
module.exports = router;
login-route.js
var express = require('express');
var router = express.Router();
var db = require('../database');
/* GET users listing. */
router.get('/login', function(req, res, next) {
res.render('login-form');
});
router.post('/login', function(req, res){
var email = req.body.email;
var password = req.body.password;
var sql='SELECT * FROM registration WHERE email_address =? AND password =?';
db.query(sql, [email, password], function (err, data, fields) {
if(err) throw err
if(data.length>0){
req.session.loggedinUser= true;
req.session.email= email;
res.redirect('/dashboard');
}else{
res.render('login-form',{alertMsg:"Your Email Address or password is wrong"});
}
})
})
module.exports = router;
logout-route.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/logout', function(req, res) {
req.session.destroy();
res.redirect('/login');
});
module.exports = router;
dashboard-route.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/dashboard', function(req, res, next) {
if(req.session.loggedinUser){
res.render('dashboard',{email:req.session.emailAddress})
}else{
res.redirect('/login');
}
});
module.exports = router;
I already see questions like this but none of the answers are working for my case problem
also I'd tried to npm clear cache --force but nothing changed
also had been uninstalled and reinstalled for node_modules , package-lock but always got same error
Change all of these:
var registrationRouter = require('./routes/registration-route').default;
to remove the .default so you just have this:
const registrationRouter = require('./routes/registration-route');
.default is something that is used with ESM modules, not with CommonJS modules.
Also, you shouldn't be using var any more. It's obsolute now. Use const for these.
I am trying to do my first API Rest and I am following some tutorials. I am requesting all the articles in a MongoDB database.
This is the code of the main:
var express = require("express"),
app = express(),
http = require("http"),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
server = http.createServer(app),
mongoose = require('mongoose');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
// Import Models and controllers
var models = require('./models/article')(app, mongoose);
var articleCtrl = require('./controllers/articleController');
// Example Route
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
articles.route('/articles/:id')
.get(articleCtrl.findById);
articles.route('/articles')
.get(articleCtrl.findAllarticles)
.post(articleCtrl.addarticle);
app.use('/api', articles);
app.use(router);
mongoose.connect('mongodb://localhost/ustcg', { useNewUrlParser: true ,useUnifiedTopology: true}, function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
});
The code of the controller is here:
// Import article and mongoose
var mongoose = require('mongoose');
var Article = mongoose.model('Article');
//GET - Return a article with specified ID
exports.findById = function(req, res) {
Article.findById(req.params.id, function(err, Article) {
if(err) return res.send(500, err.message);
console.log('GET /article/' + req.params.id);
res.status(200).jsonp(Article);
});
};
//GET - Return all articles in the DB
exports.findAllarticles = function(req, res) {
Article.find(function(err, Article) {
if(err) res.send(500, err.message);
console.log('GET /article')
res.status(200).jsonp(Article);
});
};
//POST - Insert a new article in the DB
exports.addarticle = function(req, res) {
console.log('POST');
console.log(req.body);
var Article = new Article({
title: req.body.title,
paragraphs: req.body.paragraphs
});
Article.save(function(err, Article) {
if(err) return res.send(500, err.message);
res.status(200).jsonp(Article);
});
};
The model:
//We create the model
exports = module.exports = function(app, mongoose) {
var ArticleSchema = new mongoose.Schema({
title: { type: String },
paragraphs: { type: Array },
});
mongoose.model('Article', ArticleSchema);
};
When I tried to request the following http request it send me 404 error. I can not see any logs on the console so it is not entering the methods in order to see the exception is happening so I am stucked with this...
If someone could help me it would be nice.
what is articles variable in your main file.
I tried your code in my machine and struggled with articles variable and you have extra imports which are not required.
Try following code it works fine
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var articleCtrl = require('./sample.controller');
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
router.get('/articles/:id', articleCtrl.findById);
router.post('/articles', articleCtrl.addarticle);
router.get('/articles', articleCtrl.findAllarticles)
// app.use('/api', router);
app.use(router);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
if you uncomment app.use('/api', router); then you can also use routes as localhost:3000/api/articles
I am new to Node js and trying to create a blog system. When i tried to console the posted value in categories.js file, i am getting value as "undefined". I am using post.js for adding new posts and category.js for adding new categories.
Here is my app.js file.
var createError = require('http-errors');
var express = require('express');
var expressValidator = require('express-validator');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var multer = require('multer');
var upload = multer({dest: './public/images/uploads'});
var flash = require('connect-flash');
var logger = require('morgan');
var mongodb = require('mongodb');
var db = require('monk')('localhost/nodeblog');
var indexRouter = require('./routes/index');
var posts = require('./routes/posts');
var categ = require('./routes/categories');
var app = express();
app.locals.moment = require('moment');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Session
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
// Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect Flash
app.use(require('connect-flash')());
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Make our db accessible to our router
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use('/', indexRouter);
app.use('/posts', posts);
app.use('/categories', categ);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Here is my post.js file
var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
var multer = require('multer');
var upload = multer({dest: './public/images/uploads'});
var db = require('monk')('localhost/nodeblog');
router.get('/add', function(req, res, next) {
var categories = db.get('categories');
categories.find({}, {}, function(err, categories) {
res.render('addpost', {
"title" : "Add Post",
"categories": categories
});
});
});
router.post('/add', upload.single('profileimage'), function(req, res, next) {
// Getting Form Values
var title = req.body.title;
console.log(title);
var category = req.body.category;
var body = req.body.body;
var author = req.body.author;
var date = new Date();
if(req.file) {
var profileimage = req.file.filename;
} else {
var profileimage = 'noimage.png';
}
// Form Validation
req.checkBody('title', 'Title Field is required').notEmpty();
req.checkBody('body', 'Body field is required').notEmpty();
// Check for Errors
var errors = req.validationErrors();
if(errors) {
res.render('addpost', {
"errors": errors,
"title": title,
"body": body
});
} else {
var posts = db.get('posts');
// Submitting values to DB
posts.insert({
"title": title,
"body": body,
"category": category,
"date": date,
"author": author,
"profileimage": profileimage
}, function(err, post) {
if(err) {
res.send("There is an issue in submitting the post");
} else {
req.flash('success','Post Submitted Successfully');
res.location('/');
res.redirect('/');
}
});
}
});
module.exports = router;
Here is my category file.
var express = require('express');
var router = express.Router();
router.get('/add', function(req, res, next) {
res.render('addcategory', {
"title" : "Add Category"
});
});
router.post('/add', function(req, res, next) {
// Getting Form Values
var title = req.body.title;
//console.log(req.body);
console.log(title);
});
module.exports = router;
Here is the addcategory jade file.
extends layout
block content
h1=title
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post', action='/categories/add', enctype='multipart/form-data')
.form-group
label Title:
input.form-control(name='title',type='text')
input.btn.btn-default(name='submit',type='submit',value='Save')
Here is post jade file.
extends layout
block content
h1=title
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post', action='/posts/add', enctype='multipart/form-data')
.form-group
label Title:
input.form-control(name='title', type='text')
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value= '#{category.title}') #{category.title}
.form-group
label Body
textarea.form-control(name='body', id='body')
.form-group
label Main Image
input.form-control(name='profileimage', type='file')
.form-group
label Author
select.form-control(name='author')
option(value='Deepesh') Deepesh
option(value='Sudha') Sudha
input.btn.btn-default(name='submit', type='submit', value='Save')
script(src='/ckeditor/ckeditor.js')
script
| CKEDITOR.replace('body');
I am getting req.body value in post.js. But when i tried to get the same in categories.js, i am getting the value as undefined. I need to get the value of title in categories file, where the same should work in post file.
Can you guys find me a solution for the same. I tried from my end, but didn't get a proper solution.
Routing refers to determining how an application responds to a client request to a particular endpoint. you created 2 routers for the same endpoint.
router.post('/add', function(req, res, next) {} //in categories.js and post js
once you requested data, data will go to specified address and router will take it and handle it. so you are getting the request to post.js and express handles it and then responds it. so that request will be ended.
but in categories.js you are waiting for the same request which is already gone. if you wanna test it, comment out the router.post in the post.js and and you will see that express will handle the request in categories.js.
I'm trying to make a catch-all of sorts to return data to my Author endpoint. If the url that is passed to the endpoint contains no query parameters, I want the router to return the full list of authors available. If the url contains firstName and lastName parameters, I want the controller to find the authors that match and, pass that data back to the router.
Currently if I send the urls http://localhost:3001/authors or http://localhost:3001/authors?firstName=tom&lastName=dooly, I get an error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.
Can anyone tell me why this is happening and how to fix it?
main:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
var dev_db_url = 'mongodb://localhost:27017/'
var mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(dev_db_url);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var index = require('./routes/index');
var users = require('./routes/users');
var feedEntries = require('./routes/feedEntries');
var authors = require('./routes/authors');
app.use('/', index);
app.use('/users', users);
app.use('/feedEntries', feedEntries);
app.use('/authors', authors);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
route:
var express = require('express');
var router = express.Router();
var authorController = require('../controllers/authorController');
authorController.findAuthorsByFirstAndLastName);
router.get('/', function (req, res) {
if(req.query.firstName||req.query.lastName) {
res.send(authorController.findAuthorsByFirstAndLastName(req,res));
}else{
res.send(authorController.author_list(req,res));
}
});
module.exports = router;
controller:
var Author = require('../models/author')
var async = require('async')
exports.author_list = function(req, res, next) {
Author.find({},function(err, authors) {
if (err){
res.send(err);
}
return.json(authors);
});
};
exports.findAuthorsByFirstAndLastName = function (req, res, next){
var query = {}
if(req.query.firstName||req.query.lastName) {
query = {$or:[{firstName:{$regex: req.query.firstName, $options: 'i'}},
{lastName:{$regex: req.query.lastName, $options: 'i'}}]}
}
else {
return res.status(500).send({ error: 'Unable to parse data'});
}
var firstName = req.body.firstName;
var lastName = req.body.lastName;
Author.find(query , function (err, authors) {
if(err) {
res.send(err);
}
res.json(authors);
});
};
You get cannot set headers after they are sent when you have two res.[whatever]s in your route. So you have res.send(functionCallThatAlsoDoesRes.Send). That's what's causing the error.
If you want a route to take multiple actions between the request and the response, you can write those as separate middlewares. Middlewares always take the arguments req, res, and next (a function that says to go to the next middleware in the list).
So, you might write:
authorController.findAuthorsByFirstAndLastName = function(req, res, next) {
if (!(req.query.firstName || req.query.lastName)) {
res.locals.getFullAuthorList = true
return next()
} else {
const query = /* whatever */
Author.find(query, (err, authors) => {
if (err) return next(err)
res.locals.authors = authors
next()
})
}
}
authorController.author_list = function(req, res, next) {
if (!res.locals.getFullAuthorList) return next() // if we already have authors we don't need to do anything
Author.find({}, (err, authors) => {
if (err) return next(err)
res.locals.authors = authors
next()
})
}
Then in your route, you'd say:
router.get('/', authorController.findAuthorsByFirstAndLastName, authorController.author_list, (req, res) => {
res.json({ authors: res.locals.authors })
})
If you haven't seen res.locals before, it's just a property on the response object that is available for you to attach things to. It persists throughout the request/response cycle and is cleared for each new request.
I am a begginer at node.js and trying to build a basic todo list but keep getting the error:
Cannot read property 'collection' of undefined.
Can someone please explain what im doing wrong and how to I can get my get post requests working?
Thanks for the help !
routes/index.js
var express = require('express');
var router = express.Router();
var ObjectId = require('mongodb').ObjectId
// Get Homepage
router.get('/', ensureAuthenticated, function(req, res){
req.db.collection('Todo').find().sort({"_id": -1}).toArray(function(err, result) {
//if (err) return console.log(err)
if (err) {
req.flash('error', err)
res.render('index', {
title: 'User List',
data: ''
})
} else {
// render to views/user/list.ejs template file
res.render('index', {
title: 'User List',
data: 'ldld'
})
}
})
})
function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
} else {
//req.flash('error_msg','You are not logged in');
res.redirect('/users/login');
}
}
module.exports = router;
routes/Todo.js
// list dependencies
var express = require('express');
var router = express.Router();
// add db & model dependencies
var mongoose = require('mongoose');
var Todo = require('../models/Todo');
// interpret GET /products - show product listing */
// GET intepret GET /products/edit/:id - show single product edit form */
router.get('/Todo/edit/:id', function (req, res, next) {
//store the id from the url in a variable
var id = req.params.id;
var user_id = req.cookies ?
req.cookies.user_id : undefined;
//use the product model to look up the product with this id
Todo.findById(id,user_id, function (err, product) {
if (err) {
res.send('Product ' + id + ' not found');
}
else {
res.render('edit', { Todo: Todo });
}
});
});
// POST /products/edit/:id - update selected product */
router.post('/Todo/edit/:id', function (req, res, next) {
var id = req.body.id;
var Todo = {
_id: req.body.id,
content: req.body.content,
todos : todos,
updated_at : Date.now()
};
Todo.update({ _id: id}, content, function(err) {
if (err) {
res.send('Product ' + req.body.id + ' not updated. Error: ' + err);
}
else {
res.statusCode = 302;
res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
res.end();
}
});
});
// GET /products/add - show product input form
router.get('/Todo/create', function (req, res, next) {
res.render('add');
});
// POST /products/add - save new product
router.post('/Todo/create', function (req, res, next) {
// use the Product model to insert a new product
Todo.create({
content: req.body.content,
user_id:req.cookies.user_id,
updated_at : Date.now()
}, function (err,Todo) {
if (err) {
console.log(err);
res.render('error', { error: err }) ;
}
else {
console.log('Product saved ' + Todo);
res.render('added', {Todo: Todo.content });
}
});
});
// API GET products request handler
router.get('/api/Todo', function (req, res, next) {
Todo.find(function (err, products) {
if (err) {
res.send(err);
}
else {
res.send(Todo);
}
});
});
/* GET product delete request - : indicates id is a variable */
router.get('/Todo/delete/:id', function (req, res, next) {
//store the id from the url into a variable
var id = req.params.id;
//use our product model to delete
Todo.remove({ _id: id }, function (err,Todo) {
if (err) {
res.send('Product ' + id + ' not found');
}
else {
res.statusCode = 302;
res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
res.end();
}
});
});
// make controller public
module.exports = router;
views/index.handelbars
<h2 class="page-header">Dashboard</h2>
<p> Hello {{user.name}}
<p>Welcome to your dashboard</p>
<% layout( 'layout' ) -%>
<h1 id="page-title">{{ title }}</h1>
<div id="list">
<form action="/create" method="post" accept-charset="utf-8">
<div class="item-new">
<input class="input" type="text" name="content" />
</div>
</form>
{{#each todo}}
<div class="item">
<a class="update-link" href="/edit/{{#todo._id }}" title="Update this todo item">{{todo.content}}</a>
<a class="del-btn" href="/destroy/{{ #todo._id }}>" title="Delete this todo item">Delete</a>
</div>
{{/each }}
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var Todo = require('./routes/Todo');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/Todo', Todo);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
Add the following to your app.js, right after var app = express();
app.use(function (req, res, next) {
req.db = db;
next();
});
This will create a reference to your mongoose connection in all the incoming requests, accessible via req.db.