express中用mongoose操作数据库-查、删(三)

接着之前,处理完注册的路由事件,后再做登录(查询):

//处理登录(查询)
app.post("/login", function(req, res){
	console.log(req.body)//请求的参数对象
	let {username, password: pwd} = req.body;
	//检测用户名和密码是否正确
	User.find({name: username}, function(err, doc){
		console.log(doc);
		if(err){return};
		if(!doc.length){
			res.json({
				code: 1,
				msg: "用户名错误!"
			})
		}else{
			if(pwd === doc[0].pwd){
				res.json({
					code: 0,
					msg: "登录成功!"
				})
			}else{
				res.json({
					code: 1,
					msg: "密码错误!"
				})
			}
		}
	})
})


跳转评论页后。。。

在前端页面中确定用户正确登录后跳转至评论页,首先在页面中利用模板引擎渲染出数据库中所有评论数据,前端页面:


<script type="text/javascript">
	var u = location.search.split("=")[1];
	$(".username").text(u);
//渲染评论列表
	var $list = $(".list");
	$.get("/fetchComment", function(data){
		if(!data.code && data.list.length){
			var html = template("commentList", data);
			$list.append(html).children("h2.empty").hide();
		}
	})

//删除
	$list.on("click", ".btn-danger", function(){
		$.post("/deleteComment", {_id: $(this).data("id")}, (data)=>{
			if(!data.code){
				$(this).parents("div.list-group").remove();
				if(!$list.children("div.list-group").length){
					$list.children("h2.empty").show();
				}
			}
		})
	})
</script>


后端的操作:

查询和指定数据删除(当然这里评论数据暂时是我在命令行中手动添加的):


当然在mongoose中操作数据库肯定要声明Schema,然后定义这个schema的model并在mainjs中引入:

schemas/comment.js

var mongoose = require("mongoose");
var comSchema = mongoose.Schema({
	title: String,
	content: String,
	img: String,
	author: String
});
module.exports = comSchema;
models/comment.js
var mongoose = require("mongoose");
var commentSchema = require("../schemas/comment");
var Comment = mongoose.model("comments", commentSchema);
module.exports = Comment;

main.js

//获取所有评论列表:
var Comment = require("./models/Comment");
app.get("/fetchComment", function(req, res){
	var {title, content, img, author} = req.body;
	Comment.find({}, function(err, doc){
		if(err){return};
		res.json({
			code: 0,
			list: doc
		})
	})
})
//删除指定某条评论:
app.post("/deleteComment", function(req, res){
	Comment.findOneAndRemove({_id: req.body._id}, function(err, doc){
		if(err){return};
		res.json({
			code: 0,
			msg: "删除成功!"
		})
	})
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值