订阅表设计
订阅表存储, 订阅与被订阅的关系
module.exports = app => {
const mongoose = app.mongoose
const Schema = mongoose.Schema
const subscriptionSchema = new Schema({
user: { // 订阅用户
type: mongoose.ObjectId,
ref: 'User',
required: true
},
channel: { // 订阅频道
type: mongoose.ObjectId,
ref: 'User',
required: true
},
createdAt: { // 创建时间
type: Date,
default: Date.now
},
updatedAt: { // 更新时间
type: Date,
default: Date.now
}
})
return mongoose.model('Subscription', subscriptionSchema)
}
订阅
- 将订阅者id、被订阅者id 存储在订阅关系表中
- 被订阅者的数量完成加1
订阅者的数量完成加1
await new Subscription({
user: userId, // 订阅者id
channel: channelId // 被订阅者id
}).save()
取消订阅
删除订阅关系表中的数据
- 被订阅者数量完成减1
- 订阅者数量完成减1
const record = await Subscription.findOne({
user: userId,
channel: channelId
})
await record.remove() // 删除关系表中的订阅关系
获取订阅列表
let subscriptions = await Subscription.find({
user: this.ctx.params.userId // 被订阅者 id
}).populate('channel')
获取订阅列表 并查出订阅列表里的视频信息(关联表查询)
const res = await Subscription.aggregate([
{
$match:{ user: mongoose.Types.ObjectId('63217ccac4a5416000d2bd99')}
},
{
$lookup:
{
from: "users",
localField: "channel",
foreignField: "_id",
as: "user_info"
}
},
{
$lookup:
{
from: "videos",
localField: "channel",
foreignField: "user",
as: "videos_info"
}
},
{
$lookup:
{
from: "subscriptions",
localField: "channel",
foreignField: "user",
as: "subscriptons_info"
}
},
])