我也是nodejs和expressjs猫鼬的新手,我在这些代码片段中遇到了错误。
/ * 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:无法将属性'title'设置为null 在D:\ projects \ cmscart \ routes \ admin_categories.js:142:36 在model.Query。 (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)
答案 0 :(得分:-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%>">