NodeJS Mongoose Schema'save'函数错误处理?

时间:2021-08-28 02:34:44

I am having a problem outputting an error to the user using res.send(err), which is being called in the callback of the Mongoose User Schemas 'save' function. I would like to note that when I use console.log(err), it show's the expected error (such as username is too short), but res.send is outputting '{}' in PostMan when sending a request with POST values that should cause an error.

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

Also I am wondering if I should be doing input validation in my router or in my Mongoose user schemas .pre function? Putting validation there seems correct, as it keeps my Node router file much cleaner.

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

Here is the code in question...

这是有问题的代码......

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

1 个解决方案

#1


2  

From a quick glance, it looks like you are using express. When an object or array is passed to res.send() (like in the case an error occurs), it defaults to using JSON.stringify on the object/array and sets the content-type to application/json. (Ref: http://expressjs.com/4x/api.html#res.send). The message property of an Error object is not serialized when it is passed through JSON.stringify because it is defined with enumerable being false.

从快速浏览一下,看起来你正在使用快递。当一个对象或数组传递给res.send()时(就像发生错误的情况一样),它默认在对象/数组上使用JSON.stringify并将content-type设置为application / json。 (参考:http://expressjs.com/4x/api.html#res.send)。 Error对象的message属性在通过JSON.stringify传递时不会被序列化,因为它的枚举为false。

Ex.

 $ 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? has some examples of how to make sure the message property (and others if that is what you would like) are included.

是否无法使用JSON.stringify对错误进行字符串化?有一些例子说明如何确保包含消息属性(以及其他人,如果这是你想要的)。

#1


2  

From a quick glance, it looks like you are using express. When an object or array is passed to res.send() (like in the case an error occurs), it defaults to using JSON.stringify on the object/array and sets the content-type to application/json. (Ref: http://expressjs.com/4x/api.html#res.send). The message property of an Error object is not serialized when it is passed through JSON.stringify because it is defined with enumerable being false.

从快速浏览一下,看起来你正在使用快递。当一个对象或数组传递给res.send()时(就像发生错误的情况一样),它默认在对象/数组上使用JSON.stringify并将content-type设置为application / json。 (参考:http://expressjs.com/4x/api.html#res.send)。 Error对象的message属性在通过JSON.stringify传递时不会被序列化,因为它的枚举为false。

Ex.

 $ 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? has some examples of how to make sure the message property (and others if that is what you would like) are included.

是否无法使用JSON.stringify对错误进行字符串化?有一些例子说明如何确保包含消息属性(以及其他人,如果这是你想要的)。