即使验证失败,也会在数据库中记录更新

Record updating in database even with failed validation

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

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

验证成功后,它应该创建一个 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: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection 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!');

            });

关于第一期。您有一个 if 语句来检查验证是否失败。所以你可以在if后面加上一个else语句,只有验证成功才执行你想要的代码。