I am trying to create a route to register users for my application, but I ran into a problem. When hitting the /register route, I get the following error:
TypeError: user.setPassword is not a function at
Here is my code:
models/Users.js
var mongoose = require('mongoose');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var UserSchema = new mongoose.Schema({
username: {type: String, lowercase: true, unique: true},
hash: String,
salt: String
});
UserSchema.methods.setPassword = function(password){
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};
UserSchema.methods.validPassword = function(password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
return this.hash === hash;
};
UserSchema.methods.generateJWT = function() {
// set expiration to 60 days
var today = new Date();
var exp = new Date(today);
exp.setDate(today.getDate() + 60);
return jwt.sign({
_id: this._id,
username: this.username,
exp: parseInt(exp.getTime() / 1000),
}, 'SECRET');
};
mongoose.model('User', UserSchema);
routes/index.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var mongoose = require('mongoose');
var User = mongoose.model('User');
router.post('/register', function(req, res, next){
if(!req.body.username || !req.body.password){
return res.status(400).json({message: 'Please fill out all fields'});
}
var user = new User();
user.username = req.body.username;
user.setPassword(req.body.password);
user.save(function (err){
if(err){ return next(err); }
return res.json({token: user.generateJWT()})
});
});
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');
//MongoDB Setup
var mongoose = require('mongoose');
require('./models/Users');
mongoose.connect('mongodb://localhost/images');
var passport = require('passport');
require('./config/passport');
var routes = require('./routes/index');
var app = express();
app.use(passport.initialize());
.
.
.
module.exports = app;
I'm fairly new to the MEAN stack, and after scouring the code for a few hours I can't see why things are going wrong.