【问题标题】:NodeJS Mongoose Schema 'save' function error handling?NodeJS Mongoose Schema“保存”功能错误处理?
【发布时间】:2015-07-24 04:41:01
【问题描述】:

我在使用 res.send(err) 向用户输出错误时遇到问题,该问题在 Mongoose 用户架构“保存”函数的回调中被调用。我想指出,当我使用 console.log(err) 时,它显示了预期的错误(例如用户名太短),但是 res.send 在发送带有 POST 值的请求时在 PostMan 中输出“{}”应该会导致错误。

我还想知道我是否应该在我的路由器或我的 Mongoose 用户模式 ​​.pre 函数中进行输入验证?在那里进行验证似乎是正确的,因为它使我的 Node 路由器文件更加干净。

这是有问题的代码...

app/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' });
        }
    });

});
...

app/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);

【问题讨论】:

    标签: node.js validation error-handling mongoose


    【解决方案1】:

    乍一看,您似乎使用的是 express。当一个对象或数组被传递给res.send()(就像发生错误的情况一样)时,它默认在对象/数组上使用JSON.stringify,并将内容类型设置为application/json。 (参考:http://expressjs.com/4x/api.html#res.send)。 Error 对象的 message 属性在通过 JSON.stringify 传递时不会被序列化,因为它是用 enumerable 定义的 false

    例如

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

    Is it not possible to stringify an Error using JSON.stringify? 提供了一些示例,说明如何确保包含 message 属性(如果您愿意,还可以添加其他属性)。

    【讨论】:

    • 我只是想感谢您抽出宝贵时间回复。我将检查您链接的其他 SO 问题,如果它解决了问题,我会将您的回复标记为答案。编辑:我刚刚检查了一下,是的,看来这个答案是我在调用 res.send(err) 'var stringifyError = JSON.stringify(err, ["message", "arguments", "type" 之前应该做的事情, “姓名”]); res.send(stringifyError);'
    猜你喜欢
    • 2012-08-05
    • 2014-01-07
    • 2017-10-13
    • 1970-01-01
    • 2020-04-10
    • 2016-08-18
    • 2017-10-05
    • 2012-12-28
    • 1970-01-01
    相关资源
    最近更新 更多