即使验证失败也可以记录数据库中的更新

时间:2019-01-09 13:29:33

标签: node.js express mongoose express-validator

我有一个问题,即使表单验证失败,记录也会在数据库中更改。

基本上我要做的是提交表单,从表单字段中获取数据,如果验证失败,它应该使用更改的用户输入来呈现视图,否则在输入字段中显示该记录的数据库数据。

成功验证后,它应该创建一条Flash消息显示给用户。我也在代码中添加了一些注释以进行解释。

 exports.postEditListing = (req, res, next) => {
    // get values from form input on form submission
    const updatedTitle = req.body.title;
    const updatedDescription = req.body.description;
    const updatedCategory = req.body.category;
    const image = req.file;
    const productId = req.body.productId;
    // creates slug from title field
    const updatedSlugTitle = slugify(updatedTitle, {
        lower: true,
        remove: /[*+~.()'"!:@]/g
    });
    const errors = validationResult(req);
    // if there ARE validation errors 
    if (!errors.isEmpty()) {
        // Get categories from database where they aren't equal to what the user selected in the form
        Category.find({ catName: { $ne: updatedCategory } })
        .then(cats =>{
            // render the view again showing the form data either updated by user if they edited fields or from the database
            return res.status(422).render('account/edit-listing', {
                pageTitle: 'Edit Listing',
                path: '/account/edit-listing',
                product: {
                    title: updatedTitle,
                    _id: productId,
                    category: updatedCategory,
                    description: updatedDescription
                },
                errorMessage: errors.array(),
                successMessage: null,
                pendingCount: req.pending,
                approveCount: req.approved,
                rejectCount: req.rejected,
                userId: req.user._id,
                cats: cats
            });
        })
        .catch(err => {
            console.log(err);
        })

    }
    // If validation succeeds, find the product by ID in the database
    Product.findById(productId)
        .then(product => {
            // set database fields to the updated form input values
            product.title = updatedTitle;
            product.description = updatedDescription;
            product.titleSlug = updatedSlugTitle;
            product.category = updatedCategory;
            // if there is a new image selected, delete the existing one and set a new one
            if (image) {
                fileHelper.deleteFile(product.image);
                product.image = image.path;
            }
            // save changes to database.
            return product.save()
                .then(result => {
                    // set flash message and redirect to the same page
                    req.flash('success', 'Category successfully added.');
                    res.redirect('/account/edit-listing/' + product._id);
                    console.log('success!');

                });

        })
        .catch(err => {
            // const error = new Error(err);
            // error.httpStatusCode = 500;
            // return next(error);
            console.log(err);
        });
};

第二个问题是,如果正确填写了字段,仍然会发生错误:

  

unhandledPromiseRejectionWarning:未处理的承诺拒绝。这个   由抛出异步函数引起的错误   没有障碍,或者拒绝了没有   用.catch()处理。 (拒绝ID:2)

更新:

我已经更改了上面的代码,现在我可以看到成功!即使出现验证错误,控制台也会显示,这意味着该代码块在验证失败时实际上根本不应该访问此代码的情况下运行:

        return product.save()
            .then(result => {
                // set flash message and redirect to the same page
                req.flash('success', 'Category successfully added.');
                res.redirect('/account/edit-listing/' + product._id);
                console.log('success!');

            });

1 个答案:

答案 0 :(得分:0)

关于第一期。您有一个if语句来检查验证是否失败。因此,您可以在else之后添加if语句,并仅在验证成功后才执行所需的代码。