[TOC]
### 關注與粉絲 數據模型設計
~~~
// 引入 mongoose
const mongoose = require('mongoose')
const { Schema, model } = mongoose
// 創建用戶Schema
const userSchema = new Schema({
__v: {
type: Number,
select: false
},
// 用戶名
username: {
type: String,
required: true
},
// 登錄密碼
password: {
type: String,
required: true,
select: false
},
// 用戶頭像
avatar: {
type: String,
select: false
},
// 用戶性別
gender: {
type: String,
required: true,
enum: ['male', 'female', 'secrecy'],
default: 'secrecy',
},
// 個人簡介
introduce: {
type: String
},
// 居住地
residence: {
// 字符串數組
type: [{type: String}],
select: false
},
//行業
industry: {
type: String,
select: false
},
// 職業經歷
career:{
type: [{
// 公司名稱
corporate: {type: String},
// 職位
job: {type: String}
}],
select: false
},
// 教育經歷
experience: {
type: [{
// 機構名稱
title: {type: String},
// 專業方向
major: {type: String},
// 學歷 enum: [1,2,3,4,5] 高中,本科,碩士,博士
education: { type: Number, enum: [1,2,3,4,5]},
// 入學年份
enrollment_year: { type: Number},
// 畢業年份
graduation_year: {type: Number}
}],
select: false
},
// 關注 與 粉絲
following: {
type: [{type:Schema.Types.ObjectId, ref: 'User'}],
select: false
}
})
// 生成用戶模型
module.exports = model('User', userSchema)
~~~
*****
### 關注某人
~~~
// 關注某人
async follow(ctx) {
// 當前請求 id
const { id } = ctx.params
// token 中存放的 id
const { _id } = ctx.state.user
if (id === _id) { ctx.throw(400, '自己不能關注自己~!') }
const me = await User.findById(_id).select('+following')
if (!me.following.map(id => id.toString()).includes(id)) {
// 未關注
me.following.push(id)
me.save()
ctx.body = { code: 0, message: '關注成功' }
}
}
~~~
*****
### 獲取當前登錄用戶的關注人列表
~~~
// 獲取當前登錄用戶的關注人列表
async following(ctx) {
const me = await User.findById(ctx.params.id).select('+following').populate('following')
if (!me) { ctx.throw(400, '用戶不存在!') }
ctx.body = me.following
}
~~~
*****
### 取消關注
~~~
// 取消關注
async unFollow(ctx) {
const user = await User.findById(ctx.state.user._id).select('+following')
if (!user) { ctx.throw(400, '用戶不存在') }
const index = user.following.map(id => id.toString()).indexOf(ctx.params.id)
if (index > -1) {
user.following.splice(index, 1)
user.save()
ctx.body = { code:0, messages: '取消關注成功' }
}
}
~~~
*****
### 獲取粉絲列表
~~~
// 獲取粉絲列表
async fanList(ctx) {
// 查詢所有用戶 限定條件為 following 里面的id 等于當前請求的 id
const user = await User.find({following: ctx.params.id})
ctx.body = user
}
~~~
- 序言
- ES6模塊化
- node基礎
- FS模塊
- 常用變量
- crypto加密
- 基礎
- 安裝
- 中間件
- 架構
- 結構分層
- 配置
- 路由
- 安裝路由
- 自動加載
- 獲取參數
- 路由前綴
- 路由中間件
- 控制器
- 請求
- 請求信息
- 數據庫
- mongoDB
- mongoDB原生語句
- mongoDB數據庫角色
- mongoose連接數據庫
- 自動記錄時間戳
- 模型
- mongoose模型
- 定義
- 模型初始化
- 查詢
- 新增
- 更新
- 刪除
- 隱藏字段
- 模式
- 關聯查詢
- 復雜模型
- 仿知乎個人資料建模
- 關注與粉絲
- 視圖
- 模板
- edge
- 日志
- 錯誤和調試
- 調試當前文件
- nodemon調試
- 異常處理
- Koa2錯誤處理
- 驗證
- Koa驗證器
- async-validator
- installation
- 安全
- 數據加密
- 雜項
- jwt
- koa-jwt
- env環境變量配置
- 上傳
- 分頁和模糊搜索
- 擴展
- nodemon
- bodyparser
- koaJsonError
- cross-env
- uuid生成唯一ID
- pope字符串模板引擎
- 命令行
- 部署
- 附錄
- RESTfulApi
- Http動詞
- 狀態碼
- 調用頻率限制
- 按需查詢字段
- restful分頁