I have a form I created using Twitter Bootstrap that's posting the data I put in it incorrectly to my MongoDB database. The model of the database is: ({date: 'date', link: 'string'}) and the result should look like this:
{ _id: 558a69c644c2a80985299594,
date: Mon Jul 03 1995 02:00:00 GMT+
link: 'https://www.youtu.be.com' },
But when I submit data from the form this is what I get instead:
{ _id: 558a69c644c2a80985299594,__v:0},
When I manually insert to the collection it seems to work, but I want to submit from the form.
Here is the code for the router where the POST action is handled:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
/* Database stuff */
//connect to the data store and the set up the database
var db = mongoose.connection;
//connect to the database
mongoose.connect('mongodb://localhost/Mandela_Diaries/data');
//Create a model which connects to the schema and entries collection in the Mandela_Diaries database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//The route for getting data for the database - GET form
router.get("/", function(req, res) {
//Send the current entries to the page
Entry.find({}, function(err, entries) {
console.log(entries);
if(err) {
res.status(404).json({"error": "not found", "err":err});
return;
} else {
//res.json(entries);
res.render('database', {title: 'database', entries: entries});
}
});
});
router.post('/', function(req, res) {
//console.log(date, link);
//res.redirect('form')
var newEntry = new Entry({entries: {'date': req.body.date, 'link': req.body.link}});
newEntry.save(function(err, entries){
//console.log(entries);
//res.redirect('form');
if (err !== null) {
res.status(500).json(err);
} else {
res.redirect('database');
};
});
});
module.exports = router;
And here is the code for the form which is written using the Jade template:
extends layout
block content
.container
.row
.col-s-12
h1 The Mandela Diaries Database
.row
.col-s-4
h3 Add Entry
.row
.col-s-12
form.form-inline(method='post', action='/create')
.form-group
label(for='date') Date:
input#datepicker.form-control.datepicker(type='text', value='date')
.form-group
label(for='link') Link:
input#link.form-control(type='string', value='link')
button.btn.btn-default(type='submit') Submit
.row
p
| Format options:
br
select#format
option(value='mm/dd/yy') Default - mm/dd/yy
option(value='yy-mm-dd') ISO 8601 - yy-mm-dd
option(value='d M, y') Short - d M, y
option(value='d MM, y') Medium - d MM, y
option(value='DD, d MM, yy') Full - DD, d MM, yy
option(value="'day' d 'of' MM 'in the year' yy") With text - 'day' d 'of' MM 'in the year' yy
.row
#entries.col-s-12
ul
script(type'text/javascript', scrc='../public/js/script.js')
Please help as I am running out of time on this project.
The main app.js file is below:
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 routes = require('./routes/index');
var users = require('./routes/users');
var database = require('./routes/database');
var app = express();
// 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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/public', express.static(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('public/js', express.static(path.join(__dirname + 'public/js')));
app.use('public/css', express.static(path.join(__dirname + 'public/css')));
app.use('/', routes);
app.use('/users', users);
app.use('/database', database)
app.use('/create', database)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
app.listen(8080);
console.log("The server has started");
I think the problem is with your jade template. You're not specifying the name attribute to your input elements. Try adding them
input#link.form-control(type='string', name='link')
and
input#datepicker.form-control.datepicker(type='text', name='date')
Edit:
In your post route, try changing the relevant line to this var newEntry = new Entry(req.body);
Related
I am working on a NodeJS style blog and for some reason, the variable for the category name shows up as #{category.name} whereas the other variable values actually show the values. Secondly, When I submit the image for the post, it does not upload the image. Any help to see if there might be some errors in my code would be greatly appreciated. Thank you in advance.
app.js
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 session = require("express-session");
var multer = require("multer");
var upload = multer({ dest: "./public/images" });
var expressValidator = require("express-validator");
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
var routes = require("./routes/index");
var posts = require("./routes/posts");
var categories = require("./routes/categories");
var app = express();
app.locals.moment = require("moment");
app.locals.truncateText = function(text, length) {
var truncatedText = text.substring(0, length);
return truncatedText;
};
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
// 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")));
// Express Session
app.use(
session({
secret: "secret",
saveUninitialized: true,
resave: true
})
);
// 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(require("connect-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("/", routes);
app.use("/posts", posts);
app.use("/categories", categories);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get("env") === "development") {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: {}
});
});
module.exports = app;
index.pug
extends layout
block content
if posts
each post, i in posts
.post
h1
a(href='/posts/show/#{post._id}')
=post.title
p.meta Posted in
a(href='/categories/show/#{post.category}') #{post.category} by #{post.author} on #{moment(post.date).format("MM-DD-YYYY")}
img(src='/images/#{post.mainimage}')
!=truncateText(post.body,400)
a.more(href='/posts/show/#{post._id}') Read More
addpost.pug
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.name}') #{category.name}
.form-group
label Body
textarea.form-control(name='body', id='body')
.form-group
label Main Image:
input.form-control(name='mainimage', type='file')
.form-group
label Author:
select.form-control(name='author')
option(value='Erik Robles') Erik Robles
option(value='John Doe') John Doe
input.btn.btn-default(name='submit',type='submit',value='Save')
script(src='/ckeditor/ckeditor.js')
script
| CKEDITOR.replace('body');
addcategory.pug
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')
.form-group
label Name:
input.form-control(name='name', type='text')
input.btn.btn-default(name='submit',type='submit',value='Save')
posts.js
var express = require("express");
var router = express.Router();
var multer = require("multer");
var upload = multer({ dest: "./public/images" });
var mongo = require("mongodb");
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("mainimage"), function(req, res, next) {
// Get Form Values
var title = req.body.title;
var category = req.body.category;
var body = req.body.body;
var author = req.body.author;
var date = new Date();
// Check Image Upload
if (req.file) {
var mainimage = req.file.filename;
} else {
var mainimage = "noimage.jpg";
}
// Form Validation
req.checkBody("title", "Title field is required").notEmpty();
req.checkBody("body", "Body field is required").notEmpty();
// Check Errors
var errors = req.validationErrors();
if (errors) {
res.render("addpost", {
errors: errors
});
} else {
var posts = db.get("posts");
posts.insert(
{
title: title,
body: body,
category: category,
date: date,
author: author,
mainimage: mainimage
},
function(err, post) {
if (err) {
res.send(err);
} else {
req.flash("success", "Post Added");
res.location("/");
res.redirect("/");
}
}
);
}
});
module.exports = router;
index.js
var express = require("express");
var router = express.Router();
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
/* GET home page. */
router.get("/", function(req, res, next) {
var db = req.db;
var posts = db.get("posts");
posts.find({}, {}, function(err, posts) {
res.render("index", { posts: posts });
});
});
module.exports = router;
categories.js
var express = require("express");
var router = express.Router();
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
router.get("/show/:category", function(req, res, next) {
var posts = db.get("posts");
posts.find({ category: req.params.category }, {}, function(err, posts) {
res.render("index", {
title: req.params.category,
posts: posts
});
});
});
router.get("/add", function(req, res, next) {
res.render("addcategory", {
title: "Add Category"
});
});
router.post("/add", function(req, res, next) {
// Get Form Values
var name = req.body.name;
// Form Validation
req.checkBody("name", "Name field is required").notEmpty();
// Check Errors
var errors = req.validationErrors();
if (errors) {
res.render("addpost", {
errors: errors
});
} else {
var categories = db.get("categories");
categories.insert(
{
name: name
},
function(err, post) {
if (err) {
res.send(err);
} else {
req.flash("success", "Category Added");
res.location("/");
res.redirect("/");
}
}
);
}
});
module.exports = router;
If I am missing anything, please let me know so I can make the appropriate edits. Again, Thank you.
P.S. By structure is:
routes
categores.js
index.js
posts.js
views
addcategory.pug
addpost.pug
error.pug
index.pug
layout.pug
app.js
The code I was using is old (circa 2016) and no longer works. In calling the variable name, you must remove the curly braces, hash and quotes from the first option variable. Here is how the code should read in the categories options section:
addpost.pug
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value=category.name) #{category.name}
I hope this answer helps someone struggling with the same issue.
I want to show you my error with NodeJS and MySQL.
Error is at line 45 of app.js
Cannot read property 'end' of undefined
at ServerResponse.<anonymous> (/usr/my_server/app.js:45:24)
It happen when I call a request from 'addReferFriend.js' file.
I link here the two files that I am using.
app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql= require('mysql2');
var http = require('http');
var app = express();
var addReferFriend = require('./addReferFriend');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(async function(req, res, next) {
try {
if( req.dbConnection ) {
// ensure that req.dbConnection was not set already by another middleware
throw new Error('req.dbConnection was already set')
}
let connection = mysql.createConnection({
host: 'xx',
user: 'xx',
password: 'xx',
database: 'xx'
});
res.on("finish", function() {
// end the connection after the resonponse was send
req.dbConnection.end()
});
// wait for the connection and assign it to the request
req.dbConnection = await connection.connect();
next();
} catch(err) {
next(err);
}
});
app.use('/api/addReferFriend', addReferFriend);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
var server = http.createServer(app);
server.listen(3955);
addReferFriend.js:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.post('/', function(req, res, next) {
var uid = req.body.uid;
var friendReferCode = req.body.friendReferCode;
var sqlCheckIfExist = "SELECT my_refer FROM hub_user WHERE my_refer = '" + friendReferCode + "'";
var sqlCodeCheckSameAsMine = "SELECT my_refer FROM hub_user WHERE uid = '" + uid + "'";
function checkIfUserCodeExist() {
return req.dbConnection.query(sqlCheckIfExist)
.then(([rows, fields]) => {
if (rows == 0) {
console.log("Non esiste!")
return res.send(JSON.stringify({
"status": 500,
"response": "codeNotExist"
}));
}
console.log("Esiste!")
return checkIfCodeIsSameAsMine(connection)
})
}
function checkIfCodeIsSameAsMine() {
return req.dbConnection.query(sqlCodeCheckSameAsMine)
.then(([rows, fields]) => {
if (rows == friendReferCode) {
console.log("Codice uguale!")
return res.send(JSON.stringify({
"status": 500,
"response": "sameCodeAsMine"
}));
}
console.log("Codice non uguale!")
})
}
checkIfUserCodeExist()
.catch(next)
});
module.exports = router;
I have no idea how fix this type of problem. It happen when I call the checkIfUserCodeExist() and it doesn't join into the function and it gives directly the error. I can't print any of console.log because it break.
Hope that somebody can help me with this issue.
Thanks in advance for the help,
Michele.
it seems to be req.dbConnection.end() the problem... the object dbConnection is undefined.
is it possible that the connection is closed first for some reason? so the point to closing connection is not correct?
I'm learning Node, Express, Jade & Mongodb. I'm unable to display my mongodb documents in jade. I'm unable to figure it out on my own. I'm successfully logging all documents using console.log and it display all the documents correctly. Please no mongoose or other solutions. Just how to build on this code. I already connected to the db, displayed all documents in terminal. How to be able to pass it to Jade and display it in view.jade?
Thanks.
Here is my app.js code
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Mongodb Example http://www.guru99.com/node-js-mongodb.html
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost/EmployeeDB';
MongoClient.connect(url, function(err, db) {
//Insert data into mongodb db. If the collection doesn't exist, it will be created with the first inserted document
db.collection('employee').insertOne({
number : 17,
name: "aaa"
});
//Updating Documents in a collection
db.collection('employee').updateOne(
{"name": "New Employee"}, {$set: {"name": "AA"}}
);
//Deleting Documents in a collection
db.collection('employee').deleteOne(
{ "name": "name" }
);
// no need to pass a second parameter. Just the name of the field to be deleted.
//Querying for data in mongodb db .
var cursor = db.collection('employee').find();
cursor.each(function (err, doc) {
//console.log(doc)
});
console.log("connected");
db.close();
});
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// 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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here is my index.js
var express = require('express');
var router = express.Router()
//the global str variable is accessable from anywhere and logging the db.collection but how I pass it to jade?
var str = "";
/* GET home page. and iterate, display the collection to console log. */
router.get('/', function (req, res) {
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost/EmployeeDB';
MongoClient.connect(url, function (err, db) {
var str = db.collection('employee').find();
str.each(function (err, doc) {
console.log(doc);
});
//How to pass the .db.collection documents to Jade?
res.render('index');
});
});
Here is my index.jade file
extends layout
block content
h1= title
https://naltatis.github.io/jade-syntax-docs/ Has useful information for view.jade files
index.js needs an array to hold the mongo results:
var results_from_mongo = [];
and everytime we get a result from the query, let's push it onto the array (array language for "insert an element into the array")
results_from_mongo.push(doc); //Push result onto results_array
then we must simply send it along to res.render:
res.render('index', {"results": results_from_mongo });
So in your index.js file
/* GET home page. and iterate, display the collection to console log. */
router.get('/', function (req, res) {
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost/EmployeeDB';
var results_from_mongo = [];
MongoClient.connect(url, function (err, db) {
var str = db.collection('employee').find();
str.each(function (err, doc) {
console.log(doc);
results_from_mongo.push(doc); //Push result onto results_array
});
//now we have a results array filled like this:
// results_from_mongo = ["some string", "some string", "some string"]
//so let's pass them to the jade file to render them.
res.render('index', {"results": results_from_mongo });
//this will pass the data in JSON format to the JADE file called 'index' (index.jade)
The data at this point looks like
{ "results" : ["some string", "some string", "some string"] }
and in index.jade we can do something like
extends layout
block content
h1= title
h2= "results from mongo:"
select
each mongo_result, i in results
div Result #{i} #{mongo_result}
The jade (now pug) file needs to be set up to show a table, if you want to send an array from the database to be displayed as html. Here is the relevent code that I use for my table layout in a sample index.pug file.
table
thead
tr
th Flight Date
th Tail Number
th Origin
th Destination
th Dep
th Arr
tbody
each mongo_result, i in results
tr
td= mongo_result.flight_date
td= mongo_result.tail_num
td= mongo_result.origin_airport_code
td= mongo_result.dest_airport_code
td= mongo_result.dep_time
td= mongo_result.arr_time
In this example, under the table header thead, I am setting up the captions for the header row of the table. Then under tbody, I am specifying the actual data I want pug to pull from each row of the array that is pushed to it. Pug is very sensitive to indentation with white space characters: it requires it. So you need to pay close attention to indentation or the results won't work as expected.
You can use the db() method to handle the collection:
var data = [];
router.get('/', function (req, res) {
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/'; // do not put db in url, EmployeeDB
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("EmployeeDB");
dbo.collection("employee").find({}).toArray(function(err, result) {
if (err) throw err;
data = result;
db.close();
});
});
res.render('index',{ data_employee : data });
});
});
And you must update your index.jade (or index.pug) file:
extends layout
block content
div.main
table
thead
tr
th name
th surname
tbody
each data in data_employee
tr
td= data.name
td= data.surname
I am making a user registration form witch insert a record to the mongodb. I am using there fore:
MongoDB version v2.6.11
NodeJS version v0.10.25
Express version 4.13.1
All works fine except when a use a constructor var newUser = new User({...}); it returns the error Object is not a function
The rest works fine. I get the logging before it returns the error but i don't know how to fix this.
users.js
var express = require('express');
var router = express.Router();
var User = require('../models/user');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/Registreren', function(req, res, next) {
res.render('Registration', { title: 'Registreren' });
});
router.get('/Aanmelden', function(req, res, next) {
res.render('Aanmelden', { title: 'Aanmelden' });
});
router.post('/Registreren', function(req, res, next){
// Get form value
console.log('Bericht in behandeling ...')
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password_confirm = req.body.password_confirm;
console.log('username: ' + username);
console.log('email: ' + email);
console.log('password: ' + password);
console.log('password_confirm: ' + password_confirm);
console.log('FIRST TEST: ' + JSON.stringify(req.file));
console.log('SECOND TEST: ' + req.file.profileimage);
console.log('THIRD TEST: ' + req.file.originalname);
// Check for image field
if (req.file || req.file.profileImage){
console.log('Uploading file....');
//File Info
var profileImageOrginalName = req.file.originalname;
var profileImageName = req.file.name;
var profileImageMimetype = req.file.mimetype;
var profileImagePath = req.file.path;
var profileImageExt = req.file.extension;
var profileImageSize = req.file.size;
} else{
console.log('profileImageFile not found....');
// Set default image
var profileImageName = 'noimage.png';
}
// Form validation
req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkBody('email','email is verplicht').notEmpty();
req.checkBody('email','email is niet geldig').isEmail();
req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkBody('password','Wachtwoord is verplicht').notEmpty();
req.checkBody('password_confirm','Wachtwoorden zijn niet `gelijk').equals(req.body.password);`
// Error handling
var errors = req.validationErrors();
console.log(errors);
if(errors){
console.log('Error handling....');
res.render('Registration',{
errors: errors,
email: email,
username: username,
password: password,
password_confirm: password_confirm
});
} else {
console.log('Make new User ....');
console.log('email: ' + email);
console.log('username: ' + username);
console.log('password: ' + password);
console.log('profileImageName: ' + profileImageOrginalName);
var newUser = new User({
email: email,
username: username,
password: password,
profileimage: profileImageOrginalName
});
console.log('---------------- START TEST----------------------------');
console.log('FIRST TEST: ' + JSON.stringify(newUser));
console.log('SECOND TEST: ' + newUser);
// Create User
User.createUser(newUser, function(err,user){
if(err) throw err;
});
// Succes message
req.flash('succes','Je bent succesvol aangemedld');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
APP.JS
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 session = require('express-session');
var methodOverride = require('method-override');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var flash = require('connect-flash');
var expressValidator = require('express-validator');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle file Uploads
app.use(multer({dest:'./uploads/'}).single('profileimage'));
// 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 }));
//Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Vallidator
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
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Flash
app.use(flash());
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
user.js
console.log('Mongoose Start....');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Users');
var db = mongoose.connection;
db.once('open', function (callback) {
//user Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
},
email: {
type: String,
},
profileimage: {
type: String,
}
});
console.log('Create record!');
var User = module.exports = mongoose.model('User',UserSchema);
module.exports.createUser = function(newUser, callback){
newUser.save(callback);
console.log('USER: ' + newUser)
};
});
What i have tried an read
I have read the following post:
Node.js: object is not a function
node.js express.js object is not a function call_non_function
TypeError: object is not a function Node.js
I have tried to build more logging as you can see in the scripts so i can pin point where the problem come from. But i don know how to fix this. I hope you can help me.
i get 404 error when rooting with param , whereas all other rootings defined on my rootes/users.js file work perfectly , for example i get the desire result when i call :
localhost:3000/users/users .
but get 404 when i call localhost:3000/users/users/12315454 which should correspond to the rooter /users:user_id in my users.js (you can find it below)
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.route('/users:user_id')
.get(function(req, res) {
console.log("attempting user");
User.findById(req.params.user_id, function(err, place) {
if (err)
res.send(err);
res.json(place);
});
})
.put(function(req, res) {
console.log("attempting to update user");
User.findById(req.params.user_id, function(err, place) {
if (err)
res.send(err);
user.username = req.body.name;
user.visitedPlaces = req.body.visitedPlaces;
user.likedItems = req.body.likedItems;
//user.local.email= req.body.email;
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'user updated!' });
});
});
})
.delete(function(req, res) {
User.remove({
_id: req.params.user_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
router.route('/users')
// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function(req, res) {
User.find(function(err, places) {
if (err)
res.send(err);
res.json(places);
});
});
router.route('/adduser')
.post(function(req, res) {
var user = new User();
user.password = user.generateHash (req.body.password); // set the users name (comes from the request)
user.username = req.body.username;
console.log(req.body)
console.log("user name :"+req.body.username);
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'user created!' });
});
});
module.exports = router;
my app.js config
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var mongo = require('mongoskin');
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
var port = process.env.PORT || 3030;
var router = express.Router();
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
//Facebook app credentials
var FACEBOOK_APP_ID = '******09';
var FACEBOOK_APP_SECRET = '9a*******3';
//app secret for dev = 9adfcaa6d7989d8adc12852badcf69f3
// app ifd for dev = 492502667544609
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'app')));
//var routes = require('./routes/index');
require('./config/passport')(passport); // pass passport for configuration
var users = require('./routes/users');
var places = require('./routes/places');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// set up our express application
app.use(logger('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
// required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session());
app.use(favicon());
//app.use(flash()); // use connect-flash for flash messages stored in session
// Make our db accessible to our router WARNING THIS MUST BE PUT before the rooting stuff above
app.use('/api', router);
app.use('/places', places);
app.use('/users', users);
// routes ======================================================================
require('./routes/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
app.get('/', function(req, res, next) {
res.sendfile('./app/index.html');
});
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// test authentication
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { console.log("is authenticated");
return next(); }
console.log("not authenticated");
res.redirect('/')
}
// launch ======================================================================
console.log('The magic happens on port ' + port)
module.exports = app;
Add a slash in your route, between the users and :user_id:
router.route('/users/:user_id')
^---------here