订阅表设计

订阅表存储, 订阅与被订阅的关系

  1. module.exports = app => {
  2. const mongoose = app.mongoose
  3. const Schema = mongoose.Schema
  4. const subscriptionSchema = new Schema({
  5. user: { // 订阅用户
  6. type: mongoose.ObjectId,
  7. ref: 'User',
  8. required: true
  9. },
  10. channel: { // 订阅频道
  11. type: mongoose.ObjectId,
  12. ref: 'User',
  13. required: true
  14. },
  15. createdAt: { // 创建时间
  16. type: Date,
  17. default: Date.now
  18. },
  19. updatedAt: { // 更新时间
  20. type: Date,
  21. default: Date.now
  22. }
  23. })
  24. return mongoose.model('Subscription', subscriptionSchema)
  25. }

订阅

  • 将订阅者id、被订阅者id 存储在订阅关系表中
  • 被订阅者的数量完成加1
  • 订阅者的数量完成加1

    1. await new Subscription({
    2. user: userId, // 订阅者id
    3. channel: channelId // 被订阅者id
    4. }).save()

    取消订阅

  • 删除订阅关系表中的数据

  • 被订阅者数量完成减1
  • 订阅者数量完成减1
    1. const record = await Subscription.findOne({
    2. user: userId,
    3. channel: channelId
    4. })
    5. await record.remove() // 删除关系表中的订阅关系

    获取订阅列表

    1. let subscriptions = await Subscription.find({
    2. user: this.ctx.params.userId // 被订阅者 id
    3. }).populate('channel')

    获取订阅列表 并查出订阅列表里的视频信息(关联表查询)

    1. const res = await Subscription.aggregate([
    2. {
    3. $match:{ user: mongoose.Types.ObjectId('63217ccac4a5416000d2bd99')}
    4. },
    5. {
    6. $lookup:
    7. {
    8. from: "users",
    9. localField: "channel",
    10. foreignField: "_id",
    11. as: "user_info"
    12. }
    13. },
    14. {
    15. $lookup:
    16. {
    17. from: "videos",
    18. localField: "channel",
    19. foreignField: "user",
    20. as: "videos_info"
    21. }
    22. },
    23. {
    24. $lookup:
    25. {
    26. from: "subscriptions",
    27. localField: "channel",
    28. foreignField: "user",
    29. as: "subscriptons_info"
    30. }
    31. },
    32. ])