使用MongoDB搭建博客評論多級回復(fù)

前言:剛開始寫博客,現(xiàn)在剛完成評論回復(fù)的功能,就想著記錄一下,弄了大概有兩天,很多都不懂,就自己琢磨著寫,記錄一下。

一、搭建出頁面評論回復(fù)的頁面功能

image.png

二、設(shè)計mongodb集合

1、創(chuàng)建comment評論集合

const mongoose = require('mongoose');
const commentSchema = new mongoose.Schema({
  // 用戶信息
  user: {
    // 將當(dāng)前集合和評論用戶集合關(guān)聯(lián)
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CommentUser',
    required: true
  },
  // 文章Id
  articleId: {
    type: String,
    required: true
  },
  // 評論用戶 user or admin
  type: {
    type: String,
    default: 'user'
  },
  // 內(nèi)容
  content: {
    type: String,
    maxlength: 200,
    required: true
  },
  // 創(chuàng)建時間
  enterDate: {
    type: Date,
    default: Date.now
  },
  // 贊
  like: {
    type: Number,
    default: 1
  },
  // 踩
  hate: {
    type: Number,
    default: 1
  }
});

const Comment = mongoose.model('Comment', commentSchema);
module.exports = Comment

2、創(chuàng)建reply回復(fù)集合

const mongoose = require('mongoose');
const replySchema = new mongoose.Schema({
  // 回復(fù)用戶
  formUser: {
    // 將當(dāng)前集合和用戶集合關(guān)聯(lián)
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CommentUser',
    required: true
  },
  toUser: {
    // 將當(dāng)前集合和回復(fù)用戶集合關(guān)聯(lián)
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CommentUser',
    required: true
  },
  // 內(nèi)容
  replyContent: {
    type: String,
    maxlength: 200,
    required: true
  },
  // 創(chuàng)建時間
  enterDate: {
    type: Date,
    default: Date.now
  },
  // 回復(fù)對象Id
  replyToId: {
    // 將當(dāng)前集合和評論集合關(guān)聯(lián)
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment',
    required: true
  },
  // 回復(fù)用戶 user or admin
  type: {
    type: String,
    default: 'user'
  },
  // 贊
  like: {
    type: Number,
    default: 1
  },
  // 踩
  hate: {
    type: Number,
    default: 1
  }
});
const Reply = mongoose.model('Reply', replySchema);
module.exports = Reply

三、api接口(發(fā)表評論、回復(fù)評論、獲取評論列表)

1、發(fā)表評論接口

// 發(fā)表評論
const fs = require('fs');
const path = require('path')
// 評論
const Comment = require('./../../database/comment')
// 用戶
const CommentUser = require('./../../database/commentUser');
// 獲取文件夾下的所有圖片
const public = fs.readdirSync(path.join(__dirname, '../../public/static'))

// 發(fā)表評論
module.exports = async (req, res, next) => {
  try {
    // 查詢當(dāng)前集合中是否有這個名稱
    const hasUser = await CommentUser.findOne({ name: req.body.name })
    if (hasUser === null) {
      // 獲取 0 - 20 的隨機(jī)數(shù)
      var num = parseInt(Math.random() * 21);
      // 獲取路徑
      var defaultAvatar = '/static/' + public[num];
      // 頭像路徑
      req.body.avatar = defaultAvatar;
      // 沒有就創(chuàng)建用戶
      const hasNotUser = await CommentUser.create(req.body)
      // console.log('未擁有', hasNotUser);
      req.body.user = hasNotUser._id
    } else {
      // console.log('已擁有', hasUser);
      req.body.user = hasUser._id
    }
    await Comment.create(req.body)
    res.send({
      code: 200,
      message: '發(fā)表成功'
    })
  } catch (error) {
    next(error)
  }
}
  • 描述:發(fā)表評論
  • 請求url:/comment/publishedComment
  • 請求方式:POST
  • 參數(shù):
參數(shù)名 必選 類型 描述
articleId String 文章ID
content String 評論內(nèi)容
name String 名稱
email String 郵箱
website String 網(wǎng)站

2、回復(fù)評論接口

const fs = require('fs');
const path = require('path')
// 回復(fù)
const Reply = require('./../../database/reply')
// 用戶
const CommentUser = require('./../../database/commentUser');
// 獲取文件夾下的所有圖片
const public = fs.readdirSync(path.join(__dirname, '../../public/static'))

// 回復(fù)評論
module.exports = async (req, res, next) => {
  try {
    // 查詢當(dāng)前集合中是否有這個名稱
    const hasUser = await CommentUser.findOne({ name: req.body.name })
    if (hasUser === null) {
      // 獲取 0 - 20 的隨機(jī)數(shù)
      var num = parseInt(Math.random() * 21);
      // 獲取路徑
      var defaultAvatar = '/static/' + public[num];
      // 頭像路徑
      req.body.avatar = defaultAvatar;
      // 沒有就創(chuàng)建用戶
      const hasNotUser = await CommentUser.create(req.body)
      // console.log('未擁有', hasNotUser);
      req.body.formUser = hasNotUser._id
    } else {
      // console.log('已擁有', hasUser);
      req.body.formUser = hasUser._id
    }
    await Reply.create(req.body)
    res.send({
      code: 200,
      message: '回復(fù)成功'
    })
  } catch (error) {
    next(error)
  }
}
  • 描述:回復(fù)評論
  • 請求url:/comment/replyComment
  • 請求方式:POST
  • 參數(shù):
參數(shù)名 必選 類型 描述
replyToId String 評論ID
toUser String 評論用戶ID
name String 名稱
email String 郵箱
website String 網(wǎng)站
replyContent String 回復(fù)內(nèi)容

3、獲取評論列表

// 評論
const Comment = require('./../../database/comment')
// 回復(fù)
const Reply = require('./../../database/reply')
// 獲取評論列表
module.exports = async (req, res, next) => {
  try {
    // 查詢評論集合中所有關(guān)聯(lián) user 信息的文檔數(shù)據(jù)  lean()表示 可以修改   集合默認(rèn)不可修改   
    let data = await Comment.find({ articleId: req.query.id }).populate('user', { email: 0, website: 0 }).lean();
    // 循環(huán)遍歷評論集合
    for (let item of data) {
      // 查詢回復(fù)集合中所有關(guān)聯(lián) formUser、toUser 信息的文檔數(shù)據(jù)
      let replyList = await Reply.find({ replyToId: item._id }).populate('formUser', { email: 0, website: 0 }).populate('toUser', { email: 0, website: 0 });
      // 將查詢出來的回復(fù)數(shù)據(jù) 添加到 評論集合中
      item['replyList'] = replyList;
    }
    res.send({
      code: 200,
      data: data,
      message: '成功'
    })

  } catch (error) {
    next(error)
  }
}
  • 描述:根據(jù)文章ID獲取評論列表
  • 請求url:/comment/getCommentListArticleById
  • 請求方式:GET
  • 參數(shù):
參數(shù)名 必選 類型 描述
id String 文章ID
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容