博客项目——评论功能实现

构造评论集合创建规则

// 引入mongoose模块
const mongoose = require('mongoose');

// 创建评论集合规则
const commentSchema = new mongoose.Schema({
   
	// 文章id  这里schema.types用于定义默认路径,ref是要查询的文档,这里是指要获取article id
	aid: {
   
		type: mongoose.Schema.Types.ObjectId,
		ref: 'Article'
	},
	// 评论人用户id  同理获取User的Id 
	uid: {
   
		type: mongoose.Schema.Types.ObjectId,
		ref: 'User'
	},
	// 评论时间
	time: {
   
		type: Date
	},
	// 评论内容
	content: {
   
		type: String
	}
});

// 创建评论集合
const Comment = mongoose.model('Comment', commentSchema);

// 将评论集合构造函数作为模块成员进行导出
module.exports = {
   
	Comment
}

用户登录态验证

服务端(login.js)
用户评论前需要对用户进行登录态验证,只有登录态才能使用评论功能
这里对之前login模块进行修改
req.session.role = user.role; 将用户角色放在session中(方便loginGard模块进行判断)
登录成功后,不是超级管理员则重定向页面到博客首页

//引入user用户构造集合
const {
    User } = require('../../model/user');
//引入bcrypt模块进行密码加密处理
const bcrypt = require('bcryptjs');

module.exports = async (req, res) => {
   
    const {
    email, password } = req.body
    
    if (email.trim().length == 0 || password.trim().length == 0) {
   
        return res.status(400).render('admin/error', {
    msg: '邮件或密码错误' });
    }  
   // 根据邮箱查找用户(es6写法,键值对省略),找到则为用户集合对象,否则为空
    let user =await User.findOne({
    email });
    if (user) {
   
        //密码比对成功,则登录.使用await bcrypt.compare进行加密密码比对
        let isVaild = await bcrypt.compare(password,user.password);
        if 
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值