本节重点记录一下数据库的设计。
考虑到数据之间不会有太多的关联,决定使用 MongoDB。这样在后端与数据库通信时就有两种主要方式:使用 mongodb 或者 Mongoose。参考了这篇文章,比较了一下两者的异同。我们的数据不会很复杂,并且希望更便捷地管理数据,这种情况下 Mongoose 更加适合。
对于这个项目来说,主要的表有 4 个:
- tasks 记录任务信息
- scores 用户总分
- logs 用户的打卡记录
- users 用户信息
详细字段: tasks
{
"taskId": 1,
"userId": 0,
"name": "Fruit",
"desc": "Eat fruit every day",
"type": "task",
"isOneTime": false,
"score": 2,
"maxTimes": 3,
"timesUsedToday": 2,
"createdAt": 1573404126959,
"lastUpdatedAt": 1573404126959
}
在创建 Mongoose 的 Schema 时代码如下:
// define task schema
const taskSchema = mongoose.Schema({
userId: { type: String, required: true },
taskId: { type: Number },
name: { type: String, required: true },
desc: { type: String, required: true },
type: { type: String, required: true },
isOneTime: { type: Boolean, required: true },
score: { type: Number, required: true },
maxTimes: { type: Number, required: true },
timesUsedToday: { type: Number, required: true },
createdAt: { type: Date, required: true },
lastUpdatedAt: { type: Date, required: true }
})
设置taskId
自增,需要使用 mongoose-auto-increment
插件
// ... 文件顶端引入库的代码
// define task schema
taskSchema.plugin(autoIncrement.plugin, {
model: 'TaskModel',
field: 'taskId',
startAt: 0
});
这样设置好后,每次写入新的 task 其中的 taskId 都会自增。
logs、 scores 和 users 差不太多。
其实这样的设计有一些冗余。因为 task 和 user 一一对应,score 和 user 一一对应,可以只保留 tasks 集合中的 score。
在数据库设计好之后,就可以着手开发后端功能了。后端开发过程会在下一篇文章中记录。
系列文章:
React + MobX + Electron + Node.js + MongoDB 全栈项目开发实践(零)前言
React + MobX + Electron + Node.js + MongoDB 全栈项目开发实践(一)
React + MobX + Electron + Node.js + MongoDB 全栈项目开发实践(二)允许 decorator
React + MobX + Electron + Node.js + MongoDB 全栈项目开发实践(三)使用 MobX 实现流畅数据流
React + MobX + Electron + Node.js + MongoDB 全栈项目开发实践(四)—— API 设计