[TOC]
### mongoose 復雜模型
#### 仿知乎個人資料建模
* [ ] 分析

~~~
// 引入 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
},
// 用戶性別
gender: {
type: String,
required: true,
enum: ['male', 'female', 'secrecy'],
default: 'secrecy',
},
// 個人簡介
introduce: {
type: String
},
// 居住地
residence: {
// 字符串數組
type: [{type: String}]
},
//行業
industry: {
type: String
},
// 職業經歷
Career:{
type: [{
// 公司名稱
corporate: {type: String},
// 職位
job: {type: String}
}]
},
// 教育經歷
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}
}]
}
})
// 生成用戶模型
module.exports = model('User', userSchema)
~~~
*****
* [ ] 建模思路
1. 性別建模

```
// 用戶性別
gender: {
type: String,
required: true,
enum: ['male', 'female', 'secrecy'],
default: 'secrecy',
}
```
>[danger] type: String 存儲為字符串
> enum 可枚舉類型,男 or 女 or 保密
> default 默認值為保密
*****
2. 居住地類型建模

```
// 居住地
residence: {
// 字符串數組類型
type: [{type: String}]
}
```
>[danger] 居住地,可以看出,前端傳過來的數據是一個數組,里面包含多個
> 所以設計為字符串數組類型
*****
3. 行業選擇建模

```
//行業
industry: {
type: String
}
```
*****
4. 職業經歷建模

```
// 職業經歷
Career:{
type: [{
// 公司名稱
corporate: {type: String},
// 職位
job: {type: String}
}]
},
```
*****
5. 教育經歷建模

```
// 教育經歷
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}
}]
}
```
- 序言
- 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分頁