koa
搭建服务端vs code
调试代码
npm i -S mongoose
// 安装mongoose
brew services start mongodb-community
//启动mongoDb
创建目录
|-server
|-- db
|-- model
这里mongodb
安装的时候,没有设置密码,直接连接使用;
// 文件:db/index.js const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/demo'); const db = mongoose.connection; // mongoose.connect连接mongodb,返回一个异步对象,可监听事件; db.on('connected', () => { console.log('数据库连接成功'); }); db.on('error', () => { console.log('发生错误') }) db.on('disconnected', () => { console.log('断开连接') })
在/server
目录下,运行node db/index.js
打印出“数据库连接成功”即可。
mongoose.connection
导出// 文件:新建/server/config/db.js module.exports = { port: 27017, // 默认端口 host: 'localhost', database: 'demo', // 自定义数据库名 }
// 优化/server/bd/index.js const mongoose = require('mongoose'); const DB = require('../config/db'); const { port, host, database } = DB; const DB_URL = `mongodb://${host}:${port}/${database}`; // mongoose.connect连接mongodb,返回一个异步对象,可监听事件; mongoose.connect(DB_URL); const db = mongoose.connection; db.on('connected', function() { console.log(`Mongoose connection open to ${DB_URL}`) }) db.on('error', function(err){ console.log(`Mongoose connection error: ${err}`) }) db.on('disconnected', function() { console.log('Mongoose connection disconnected') }) module.exports = mongoose;
// 文件:server/model/user.js const mongoose = require('../db/index'); const Schema = mongoose.Schema; // 定义数据结构 const userSchema = Schema({ __v: { // __v双下划线,默认生成 select: false // select:false查询不会将该字段查出 }, avatar: { type: String }, account: { type: String, required: true }, password: { type: String, required: true, select: false }, alias: { type: String }, telephone: { type: String, select: false }, email: { type: String, select: false } }) // 后续的增删改查是通过导出的User Model实现。 module.exports = mongoose.model('User', userSchema);
// 文件:server/model/approve.js const mongoose = require('../db/index'); const Schema = mongoose.Schema; const approveSchema = Schema({ name: { type: String, required: true }, category: { type: String, required: true }, description: { type: String, select: false }, author: { type: Schema.Types.ObjectId, // 注意作者 ref: 'User', required: true }, createtime: { type: Number, required: true }, latesttime: { type: Number, required: true } }) module.exports = mongoose.model('Approve', approveSchema);
Schema
定义参考文档approveSchema
中author
的type:Schema.Types.ObjectId, ref='User'
,新增审批的时候,将用户的Id
赋值给author
即可,后续通过populate
,可以通过用户Id查出用户信息替换该Id
赋值给author
字段。mongooseSchema
定义参考文档
mongoose一对多关系方案