【问题标题】:TypeError: Cannot set property 'title' of nullTypeError:无法将属性“标题”设置为 null
【发布时间】:2019-04-18 22:20:54
【问题描述】:

我也是 nodejs 和 expressjs mongoose 的新手,我在这些 sn-ps 中遇到了错误。

/* POST 编辑类别*/

router.post('/edit-category/:id', function (req, res) {

    var title = req.body.title;
    var slug =title.replace(/\s+/g, '-').toLowerCase();


    var id = req.body.id;


    var errors = req.validationErrors();
    if (errors) {
        res.render('admin/edit_category', {
            errors: errors,
            title: title,
            id: id
        });
    } else {
        Category.findOne({slug:slug, _id: { '$ne': id } }, function (err, category) {

            if (category) {
                req.flash('danger', ' Category Title exists , choose another.');
                res.render('admin/edit_category', {
                    title: title,
                    id: id
                });
            }
            else {
                Category.findById(id, function (err, category) {
                    if (err) {
                        return console.log(err);
                    }
                    category.title = title;
                    category.slug = slug;


                    category.save(function (err) {
                        if (err)
                            return console.log(err);
                        req.flash('success', 'Category editted!');
                        res.redirect('/admin/categories/edit-category/' +id);

                    });
                });
            }
        });
    }


});

TypeError:无法将属性“标题”设置为 null 在 D:\projects\cmscart\routes\admin_categories.js:142:36 在模型.查询。 (D:\projects\cmscart\node_modules\mongoose\lib\model.js:3407:16) 在 D:\projects\cmscart\node_modules\kareem\index.js:259:21 在 D:\projects\cmscart\node_modules\kareem\index.js:127:16 在 _combinedTickCallback (内部/进程/next_tick.js:132:7) 在 process._tickCallback (internal/process/next_tick.js:181:9)

【问题讨论】:

  • console.log(req.body) 的值是多少?
  • 但是我用过这个
  • 添加行:console.log(req.body); 以上:var title = req.body.title;。尝试向该端点发出 post 请求并向我们展示结果。
  • { title: 'food3' } 如果我将 title 的值输入为 food3
  • 它最有可能来自category.title = title; 这一行 - 你会添加一个console.log(category) 行并让我们知道category 是什么吗?

标签: node.js express mongoose


【解决方案1】:

使用

res.redirect('/admin/categories/edit-category/' +category.slug);

而不是

res.redirect('/admin/categories/edit-category/' +id);

并在 edit-category.ejs(您的编辑页面)上方提交按钮 <input type="hidden" name="id" value="<%=id%>">

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 2021-05-23
    • 2019-10-24
    • 2020-02-19
    • 2023-03-06
    • 1970-01-01
    • 2014-08-20
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多