Express和节点将错误消息发送到车把视图

时间:2019-02-17 20:07:21

标签: node.js express

如何为电子邮件unique: true选项的视图输出验证错误?在我的车把视图中,我从errors传递了var errors = req.validationErrors();并将其显示在有效的视图中。但是用于唯一性的电子邮件验证将转到user.save((err),并将其发送到控制台。验证工作正常,如果电子邮件重复,则不会创建任何用户。我只是想将错误消息发送到视图。我可以为req.check做一个unique: true吗?

const UserSchema = new Schema({
    email: { type: String, index: { unique: true } },
    password: { type: String, required: true }
});

我的createUser.handlebars视图

{{#if errors}}
  <section class="errors">
    <ul>
      {{#each errors}}
        <li>{{this.msg}}</li>
      {{/each}}
    </ul>
  </section>
{{/if}}

createUser函数

module.exports.createUser =
    (req, res, next) => {

        let user = new User({
            email: req.body.email,
            password: req.body.password
        });


        req.check('email', 'Invalid email').isEmail(); 
        req.check('password', "Passwords must match").isLength({min: 6}).equals(req.body.passwordConfirmation);

        var errors = req.validationErrors();  // save any error messages

        // check if there are any errors
        if (errors) {
            req.session.errors = errors; 

            req.session.success = false;
            return res.redirect('/users/new'); 
        } else {
            req.session.success = true;
        }
        // save the user
        user.save((err) => {
            if (err) {
                console.log("Error : %s ", err);
            }
            // set the session messages back to null and redirect
            req.session.success = null;    
            req.session.errors = null;                    
            res.redirect('/');
        });
    };    

2 个答案:

答案 0 :(得分:0)

如果我没记错的话,那么您正在使用express-validator进行验证。问题是您要混合两件事:表单验证和数据库约束。

唯一性不是数据项的固有属性,不能独立于整个集合进行检查。

您只能使用对数据库的调用来检查唯一性。如果您的数据库架构将此属性/列定义为唯一,那么尝试存储它将引发错误(至少在基于SQL的数据库和MongoDB中)。

答案 1 :(得分:0)

您可以像这样创建自定义验证检查

OverflowError                             Traceback (most recent call last)
~\anaconda\lib\site-packages\astropy\io\ascii\core.py in _convert_vals(self, cols)
    971                         raise TypeError('converter type does not match column type')
--> 972                     col.data = converter_func(col.str_vals)
    973                     col.type = converter_type

~\anaconda\lib\site-packages\astropy\io\ascii\core.py in generic_converter(vals)
    915     def generic_converter(vals):
--> 916         return numpy.array(vals, numpy_type)
    917 

OverflowError: Python int too large to convert to C long

During handling of the above exception, another exception occurred:

KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-54-f59c9c65394f> in <module>
      3 from astropy.io import ascii
      4 
----> 5 data = ascii.read(r"C:\....", format='cds')
      6 # Table.read() instead of ascii.read(), the url instead of the file path, and "cds" for format
      7 

~\anaconda\lib\site-packages\astropy\io\ascii\ui.py in read(table, guess, **kwargs)
    321         else:
    322             reader = get_reader(**new_kwargs)
--> 323             dat = reader.read(table)
    324             _read_trace.append({'kwargs': copy.deepcopy(new_kwargs),
    325                                 'Reader': reader.__class__,

~\anaconda\lib\site-packages\astropy\io\ascii\cds.py in read(self, table)
    325                     return table
    326         else:
--> 327             return super().read(table)

~\anaconda\lib\site-packages\astropy\io\ascii\core.py in read(self, table)
   1228             self.meta['table'].update(self.header.table_meta)
   1229 
-> 1230         table = self.outputter(cols, self.meta)
   1231         self.cols = self.header.cols
   1232 

~\anaconda\lib\site-packages\astropy\io\ascii\core.py in __call__(self, cols, meta)
   1000         # Sets col.data to numpy array and col.type to io.ascii Type class (e.g.
   1001         # FloatType) for each col.
-> 1002         self._convert_vals(cols)
   1003 
   1004         t_cols = [numpy.ma.MaskedArray(x.data, mask=x.mask)

~\anaconda\lib\site-packages\astropy\io\ascii\core.py in _convert_vals(self, cols)
    972                     col.data = converter_func(col.str_vals)
    973                     col.type = converter_type
--> 974                 except (TypeError, ValueError) as err:
    975                     col.converters.pop(0)
    976                     last_err = err

KeyboardInterrupt: 

我在路由器中写这个并在控制器中定义函数

check('email').custom(value => {
        return userController.findByEmail(value).then( user => {
            if(user){
                return Promise.reject('this email already exists')
            }
        })
})
相关问题