NodeJS Mongoose Schema“保存”functionerror handling?

我有一个问题向用户输出一个错误,使用res.send(err),这是在Mongoose用户模式的“保存”function的callback中被调用。 我想要注意的是,当我使用console.log(err)时,它显示预期的错误(如用户名太短),但res.send在PostMan发送请求时使用POST值输出“{}”应该会导致错误。

另外我想知道是否应该在我的路由器或我的Mongoose用户模式.pre函数进行inputvalidation? 把validation看起来是正确的,因为它使我的节点路由器文件更清洁。

这里是有问题的代码…

应用程序/路由/ 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' }); } }); }); ... 

应用程序/模型/ 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); 

从一眼就可以看出你正在使用快递。 当一个对象或数组传递给res.send() (就像发生错误时),它默认使用对象/数组的JSON.stringify ,并将content-type设置为application/json 。 (参考: http : //expressjs.com/4x/api.html#res.send )。 Error对象的消息属性在通过JSON.stringify传递时不会被序列化,因为它被定义为enumerablefalse

防爆。

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

是不是可以使用JSON.stringifystring化错误? 有一些如何确保message属性(和其他人,如果这是你想要的)的例子包括在内。