NodeJS Mongoose Schema "save" error handling function?

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 { //User saved! res.json({ message: 'User created' }); } }); }); ... 

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); 
+6
source share
1 answer

With a quick look, it looks like you are using express. When an object or array is passed to res.send() (for example, in case of an error), it by default uses JSON.stringify in the object / array and sets the content type to application/json . (Link: http://expressjs.com/4x/api.html#res.send ). The message property of the Error object is not serialized when passed through JSON.stringify , because it is defined with enumerable false .

Ref.

  $ node > var err = new Error('This is a test') undefined > console.log(JSON.stringify(err)) {} undefined 

Is it impossible to consolidate the error using JSON.stringify? , there are some examples of how to verify the message property (and others, if that's what you would like) included.

+2
source

All Articles