NodeJS博客实战19_博客内容修改和删除
源码地址:https://github.com/RidingACodeToStray/Nodejs_blog
1.主要功能
1)编辑内容页面的渲染
2)编辑内容的分类加载
3)编辑内容的的提交验证
4)内容的删除
2.实现思路
1.使用findOne方法根据传过来的id查找相应的内容并返回
2.使用模板渲染将返回的内容渲染到页面
3.查找分类并渲染到列表上
4.使用populate联表查到分类的id,使用模板渲染判断选中分类
3.相关代码
1)内容修改渲染数据
routers/admin.js
//内容修改
router.get('/content/edit',function(req,res){
var id = req.query.id || '';
var categories = [];
Category.find().sort({_id:1}).then(function(res){
categories = res;
return Content.findOne({
_id:id
}).populate('category');
}).then(function(content){
if(!content){
res.render('admin/error',{
userInfo:userInfo,
message:'指定内容不存在'
});
return Promise.reject();
} else{
res.render('admin/content_edit',{
userInfo:req.userInfo,
categories:categories,
content:content
})
}
})
});
2)内容修改提交保存:
routers/admin.js
//内容修改保存
router.post('/content/edit',function(req,res){
var id = req.query.id || '';
if (req.body.title == '') {
res.render('admin/error',{
userInfo:req.userInfo,
message:'标题不能为空'
})
return;
}
if (req.body.content == '') {
res.render('admin/error',{
userInfo:req.userInfo,
message:'内容不能为空'
})
return;
}
Content.update({
_id:id
},{
category:req.body.category,
title:req.body.title,
desciption:req.body.desciption,
content:req.body.content
}).then(function(){
res.render('admin/success',{
userInfo:req.userInfo,
message:'内容保存成功',
url: '/admin/content/edit?id=' + id
})
})
})
3)内容删除
routers/admin.js
//内容删除
router.get('/content/delete',function(req,res){
var id = req.query.id || '';
Content.remove({
_id:id
}).then(function(){
res.render('admin/success',{
userInfo:req.userInfo,
message:'删除成功',
url:'/admin/content'
});
})
})
4)渲染页面代码
views/admin/content_edit.html
{% extends 'layout.html' %}
{% block main %}
<div class="a-userNav">
<span><a href="/">管理首页</a></span>
<span> / </span>
<span>内容修改 - {
{content.title}}</span>
</div>
<form style="padding-left: 50px;margin-top: 20px;" method="post">
{
{content.category._id.toString()}}
<div>
<label for="category">分 类:</label>
<select name="category" id="category" style="width: 200px;">
{% for category in categories %}
{% if content.category._id.toString() == category._id.toString() %}
<option value="{
{category.id}}" selected>{
{category.name}}</option>
{% else %}
<option value="{
{category.id}}">{
{category.name}}</option>
{% endif %}
{% endfor %}
</select>
</div>
<div>
<label for="title">内容标题:</label>
<input type="text" name="title" id="title" style="width: 200px;" value="{
{content.title}}">
</div>
<div>
<label for="desc">简 介:</label>
<input type="desc" name="desciption" id="desciption" style="width: 200px;" value="{
{content.desciption}}">
</div>
<div>
<label for="content" style="vertical-align: top;">内 容:</label>
<textarea type="content" name="content" id="content" style="width: 200px;" rows="4">{
{content.content}}</textarea>
</div>
<button type="submit">提交</button>
</form>
{% endblock %}
还没有评论,来说两句吧...