HTTP post request parameters doesn't change default values of Mongoose schema - node.js

I created two Mongoose schemas and want to test them with Postman.
When I send a post HTTP request my parameters doesn't change the default value from the AnimalSchema nor does at StorySchema.
var mongoose = require('mongoose');
var AnimalSchema = new mongoose.Schema({
name: {type : String, default: ""},
audio: {type : String, default: ""},
image: {type : String, default: ""}
});
mongoose.model('Animal', AnimalSchema);
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Animal = mongoose.model('Animal');
var Story = mongoose.model('Story');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/animals', function(req, res, next){
Animal.find(function(err, animals){
if(err){
return next(err);
}
res.json(animals);
});
});
router.post('/animals', function(req, res, next){
var animal = new Animal(req.body);
animal.save(function(err,animal){
if(err){return next(err);}
res.json(animal);
});
});
router.get('/stories', function(req, res, next){
Story.find(function(err, stories){
if(err){return next(err);}
res.json(stories);
});
});
router.post('/stories', function(req, res, next){
var story = new Story(req.body);
story.save(function(err, story){
if(err){return next(err);}
res.json(story)
});
});
module.exports = router;
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 app = express();
var mongoose = require('mongoose');
// connect MongoDB
mongoose.connect('mongodb://localhost/stuckyToys', function(err,db){
if (!err){
console.log('Connected to /stuckyToys!');
} else{
console.dir(err); //failed to connect
}
});
require('./models/Animals');
require('./models/Stories');
var routes = require('./routes/index');
var users = require('./routes/users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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')));
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 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;
I think I made an error in my app.js file. But not sure where it is.
Anyone knows what I did wrong?

I would do something like
{*(Model)}.findById(id, function(err, animal) {
if (err) console.log(err);
{update new values here in animal with the ones you are receiving in the request}
animal.save(function(err) {
if (err) console.log(err);
});
});

Related

How can i get values of parameters using postman?

I am working on Node JS and PostgreSQL and I am creating REST web service using this. I have created a post method and calling web service through POSTMAN but unable to get parameter values in my function. Web service inserting null value in my PostgreSQL table. I am using Visual studio 2015 unable to debug code. How can I achieve this ?
queries.js
var promise = require('bluebird');
var options = {
// Initialization Options
promiseLib: promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://test:12345#localhost:8080/test';
var db = pgp(connectionString);
function getAllTask(req, res, next) {
debugger;
db.any('select * from tasklist')
.then(function (data) {
res.status(200)
.json({
status: 'success',
message: 'Retrieved ALL puppies',
data: data
});
})
.catch(function (err) {
return next(err);
});
}
function addTask(req, res, next) {
debugger;
//var task_name = req.param('task_name');
//var task_type = req.param('task_type');
var task_name = req.body.task_name;
var task_type = req.body.task_type;
console.log(req.body);
db.func('inserttask', [task_name, task_type])
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one task'
});
})
.catch(function (err) {
return next(err);
});
}
module.exports = {
getAllTask: getAllTask,
addTask: addTask
};
index.js
var express = require('express');
var router = express.Router();
var db = require('../queries');
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/api/tasklist', db.getAllTask);
router.post('/api/addtask', db.addTask);
module.exports = router;
server.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 index = 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 iblic
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
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 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;
I am assuming that you are already using express js as framework for node js.
First of all you need to install body-parser module from npm:-
$ npm install body-parser --save
Once you have installed body-parser, add following code once after you have defined app variable:-
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // to support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // to support encoded bodies
Now you can access your post request body paramters as req.body.task_name and req.body.task_type
Hope it works and I am sorry if I have misunderstood your question.
You need to add Content-Type: application/json inside Headers when you send request through POSTMAN.

SyntaxError: Unexpected token )

I am using Cassandra + Node.js to create an app, but I am receiving an error for this code:
C:\Users\userx\node-cassandra\app.js:44
app.post('/',new);
^
SyntaxError: Unexpected token )
at Module._compile (module.js:545:28)
This is my code
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 helenus = require('helenus');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
var pool = new helenus.ConnectionPool({
hosts : ['localhost:9160'],
keyspace : 'webinar',
cqlVersion : '3.0.0',
//user : 'test',
//password : 'test1233',
//timeout : 3000
//cqlVersion : '3.0.0' // specify this if you're using Cassandra 1.1 and want to use CQL 3
});
pool.connect(function(err){
if(err){
throw(err);
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('cassandra',pool);
// 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')));
app.get('/', routes.index);
app.post('/', new);
app.delete('/', delete);;
// 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 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;
});
index.js
exports.index = function(req, res, next){
req.app.get('cassandra').cql('SELECT * FROM users LIMIT 10',function(err, users){
if(err){
return next(err);
}
res.render('index', { title: 'Users', users: users });
});
};
exports.new = function(req, res, next){
var insert = 'UPDATE users SET first_name=?, last_name=? WHERE email=?',
params = [req.body.first_name, req.body.last_name, req.body.email];
req.app.get('cassandra').cql(insert, params, function(err, users){
if(err){
return next(err);
}
res.redirect('/');
});
};
exports.delete = function(req, res, next){
var remove = 'DELETE FROM users WHERE email=?',
params = [req.body.email];
req.app.get('cassandra').cql(remove, params, function(err, users){
if(err){
return next(err);
}
res.redirect('/');
});
};
Error
SyntaxError: Unexpected token )
i just tried to change the app.post('/',routes.new);
but it showed inheritance mustnot be done
Please tell me where is my mistake
new is a reserved word in ECMAScript. I don't think you will be able to use it as a member name as it is being interpreted as creating a new object.

Express.js request.body not working

I have a simple form for login, the problem is when i press "Submit", the request.body on server side is empty.I saw that bodyParser is a fundamental part but in my case it's declared before the routes, so i think the problem is another. this is my server page App.js
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = 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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
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 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 index.js
var express = require('express');
var router = express.Router();
function Login(req, res){
var mongoClient = require('mongodb').MongoClient;
mongoClient.connect('mongodb://localhost:27017/squaredDB', function(err, db) {
if(err) throw err;
db.collection('users').find({email: req.body.email}, function(err, data){
console.log(req.body);
});
});
}
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
Login(req, res);
res.render('app-home', { title: '' });
});
module.exports = router;
this is my jade template form:
form(method="post" action="/")
label Email
input(type="text" placeholder="Email")
label Password
input(type="password" placeholder="Password")
input(type="submit" value="login")
You're missing name attributes for your input fields in your template. Without those the browser won't submit them in the form.
Add a name attribute to your input field it will now be able to access the field via request like req.body.name
<form action="/", method="POST">
<input type="text" placeholder="name" name="name">
<button type="submit">Submit</button>
</form>

NodeJS routing to 404 instead of correct page

I have the following code. I am trying to get it to show the users in my db when I go to http://localhost:4000/user, however all I get is 404. I would appreciate some help as I'm clearly not understanding something.
app.js
var express = require('express');
var path = require('path');
var logger = require('morgan');
var index = require('./routes/index');
var user = require('./routes/users');
var mongoose = require('mongoose');
var app = express();
//This is all setup code.
// view engine setup
app.set('view engine','ejs')
app.set('views', path.join(__dirname, 'views'));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/user',user);
// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
// render the error page
res.status(err.status || 500);
res.render('error');
});
//Mongo code
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/db1')
.then(() => console.log('Connected to db succesfully'))
.catch((err) => console.error(err));
module.exports = app;
app.listen(4000, function () {
console.log('listening on port 4000!')
})
routes/user.js
var express = require('express');
var router = express.Router();
var userModel = require('../models/users.js');
/* GET home page. */
router.get('/user', function(req, res, next) {
console.log("get request made");
});
router.route('/user')
.get(function(req, res) {
User.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
.post(function(req, res) {
var user = new User(); // create a new instance of the Bear model
user.firstNamename = req.body.firstName; // set the bears name (comes from the request)
user.lastName=req.body.lastName;
user.email=req.body.email;
user.save(function(err) {
if (err)
res.send(err);
console.log("User created");
});
})
module.exports = router;
model/users.js
var mongoose = require('mongoose');
// Create a user schema
var userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
});
module.exports = mongoose.model('User', userSchema);
Three problems here:
first you've required ./routes/users but your route file is user.js, so it should be:
var user = require('./routes/user');
second, when you have mounted user middleware on your app you choose to prepend /user to all of user routes(app.use('/user', user);); so when you say:
router.route('/user').get(function ...
it responds to /user/user routes. so the right implementation is:
router.route('/').get(function ...
this responds to /user
third, semicolon before your post request should be removed.
Note that router.route('/').get(function... is exactly the same as router.get('/', function ... . we use first pattern for chaining different http verbs to one route. but semicolon destroyed the linking:
router
.route('/')
.get(function ...)
.post(function ...)
.delete(function ...);

It doesn't validate when If I write things to form inputs are even correct. It gives all errors everytime

I m learning from fast record on youtube. calls "Learn NodeJS building 10 projects". he is doing that at 15. video. Well this is my first post here. dont yell me cuz its my first message here. and please use easy english :) salute from turkey.
///THIS IS THE APP.JS
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
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 multer
//app.use(multer({dest:'./uploads'}));
var upload = multer({ dest: './uploads' });
// 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-session
app.use(session({
secret:'secret',
saveUninitialized: true,
resave:true
}));
// passport
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
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// connect-flash
app.use(flash());
// express-messages
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
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;
------------------------------
THIS IS THE USERS.JS
------------------------------
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/yenihesap', function(req, res, next) {
res.render('yenihesap',{
'title': 'Yeni Hesap Aç'
});
});
router.get('/giris', function(req, res, next) {
res.render('giris',{
'title': 'Giriş Yap'
});
});
router.get('/sifremiunuttum', function(req, res, next) {
res.render('sifremiunuttum',{
'title': 'Şifremi Unuttum'
});
});
router.post('/yenihesap', function(req, res, next){
// get form values
var name = req.body.name;
var lastname = req.body.lastname;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
// form validation
req.checkBody('name', 'Lütfen isminizi giriniz').notEmpty();
req.checkBody('lastname', 'Lütfen soyadınızı giriniz').notEmpty();
req.checkBody('email', 'Lütfen email adresinizi giriniz').notEmpty();
req.checkBody('email', 'Bu bir email adresi değil!').isEmail();
req.checkBody('password', 'Lütfen şifrenizi giriniz').notEmpty();
req.checkBody('password2', 'Şifreniz eşleşmiyor!').equals(req.body.password);
// check for errors
var errors = req.validationErrors();
if(errors){
res.render('yenihesap',{
errors: errors,
name: name,
lastname: lastname,
email: email,
password: password,
password2: password2
});
}else{
var newUser = new User({
name: name,
lastname: lastname,
email: email,
password: password
});
// create user
//User.createUser(newUser, function(err, user){
// if(err) throw err;
// console.log(user);
//});
//succes message
req.flash('success', 'Başarıyla kayıt oldunuz');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
this is the jade file
when even i full up to input forms correctly, all errors that i have. i dont understand why
I found the problem. Its about the multer. first of all it wasnt work with that code at the beggining
//handle file uploads multer
app.use(multer({dest:'./uploads'}));
the multer was giving me error and changed it to that
//handle file uploads multer
var upload = multer({ dest: './uploads' });
and this time multer had me this question problem that body parser wasnt work. so I changed to that. and it fixed my problem. I found it another question on stackover: typeerror: app.use() requires middleware function
//handle file uploads multer
app.use(multer({dest:'./uploads/'}).single('singleInputFileName'));
I m happy to joined this site. Its obviously perfect that people help each other. see you on next problems :)

Resources