I had a problem with outputting an error to the user using res.send (err), which is called in the callback of the Save function of the Mongoose function. I would like to note that when I use console.log (err), it shows the expected error (for example, the username is too short), but res.send displays "{}" in PostMan when sending a request with POST values, which should cause a mistake.
I also wonder if I should do input validation in my router or in my Mongoose.pre user schema? The validation there seems correct, as it makes my Node file cleaner.
Here is the code in question ...
Application / routes / apiRouter.js
var User = require('../models/User'); var bodyParser = require('body-parser'); ... apiRouter.post('/users/register', function(req, res, next) { var user = new User; user.name = req.body.name; user.username = req.body.username; user.password = req.body.password; user.save(function(err) { if (err) { console.log(err); res.send(err); } else {
application / models / user.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt-nodejs'); var validator = require('validator'); var UserSchema = new Schema({ name: String, username: { type: String, required: true, index: {unique: true} }, password: { type: String, required: true, select: false } }); UserSchema.pre('save', function(next) { var user = this; if (!validator.isLength(user.name, 1, 50)) { return next(new Error('Name must be between 1 and 50 characters.')); } if (!validator.isLength(user.username, 4, 16)) { return next(new Error('Username must be between 4 and 16 characters.')); } if (!validator.isLength(user.password, 8, 16)) { return next(new Error('Password must be between 8 and 16 characters.')); } bcrypt.hash(user.password, false, false, function(err, hash) { user.password = hash; next(); }); }); UserSchema.methods.comparePassword = function(password) { var user = this; return bcrypt.compareSync(password, user.password); }; module.exports = mongoose.model('User', UserSchema);