使用Mongoose對MongoDB進行操作
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test',{
})
Mongoose中的Schema
- 定義Schema
categorySchema
const categorySchema = new mongoose.Schema({name:String,description: String,createdAt:{type: Date,default: Date.now}
});
- 通過model方法獲得該模型
const Category = mongoose.model('Category', categorySchema);
- 實例化一個新的對象來新增數據
const category = new Category({name: 'test',description: 'test category'
});
- 通過save方法,保持對象到數據庫中
category.save(err=>{if(err){console.error(err);return}console.log('saved');
})
- 直接通過模型的Create方法
Category.create({name:'test',description: 'test category'
}, (err, category)=>{if(err){console.error(err);} else {console.log(category)}
});
- 通過find方法,查詢name='test’的結果
Category.find({name:'test'
}, (err, res) =>{if(err){console.error(err)} else{console.log(res);}
});
- 刪除數據
Category.remove({name:'test'
}).then(()=>{
})
- 更新數據
Category.update({name:'test'
},{name:'test1',description: 'test1'
}).thenm(()=>{})
栗子
-
目錄結構如下
-
說明:
course.js
:定義了Course表的結構
coon.js
:連接數據庫
db.js
:接口的封裝
app.js
:負責路由處理和基本的koa相關的配置 -
/mongoDB/model/course.js
const mongoose = require('mongoose');
const timeRangeSchema = new mongoose.Schema({hour: {type: Number,max: 24,min: 8},minute: {type: Number,max: 59,min: 0},time: {type: Number,get() {return this.get('hour') * 100 + this.get('minute');}}
});const courseSchema = new mongoose.Schema({name: String,startTime: timeRangeSchema,endTime: timeRangeSchema
})
const Course = mongoose.model('Course', courseSchema);module.exports = Course;
db.js
const Course = require('./model/course');const getCourseList = async () => {return await Course.find({}).sort({'startTime.time': 1});
}const getCourseById = async (id) => {return await Course.findById(id);
}const getCourseByTime = async (start, end, weekday) => {return await Course.find({weekday: weekday}).where('startTime.time').gte(start.hour * 100 + start.minute).where('endTime.time').lte(end.hour * 100 + end.minute);
}
const addCourse = async (course) => {const { name, weekday, startTime, endTime } = course;const item = await getCourseByTime(startTime, endTime, weekday);if (item) {throw new Error('當前時間段已經安排了課程');}return await Course.create(course);
}const updateCourse = async (id, course) => {return await Course.update({_id: id}, course);
}const removeCourse = async (id) => {return await Course.remove({_id: id});
}module.exports = {getCourseList,getCourseById,addCourse,updateCourse,removeCourse
}
conn.js
const mongoose = require('mongoose');const connect = async () => {await mongoose.connect('mongodb://localhost/course', {useNewUrlParser: true,useUnifiedTopology: true});
}const close = async () => {await mongoose.connection.close();
}module.exports = { connect, close }
app.js
const koa = require('koa');
const app = new koa();
const router = new require('koa-router')();
const bodyParser = require('koa-bodyparser');
const {getCourseList,getCourseById,addCourse,updateCourse,removeCourse
} = require('./db');const {connect,close
} = require('./conn');const JSON_MIME = 'application/json';router.get('/course', async ctx => {ctx.type = JSON_MIME;ctx.body = {status: 0,data: await getCourseList()}
});router.get('/course/:id', async ctx => {ctx.type = JSON_MIME;ctx.body = {status: 0,data: await getCourseById(ctx.params.id)}
});router.post('/course', async ctx => {ctx.type = JSON_MIME;await addCourse(ctx.body);ctx.body = {status: 0}
});router.put('/course/:id', async ctx => {await updateCourse(ctx.params.id, ctx.body);ctx.body = {status: 0}
});router.delete('/course/:id', async ctx => {await removeCourse(ctx.params.id);ctx.body = {status: 0}
})app.use(async (ctx, next) => {await connect()await next()await close()
})app.use(bodyParser());
app.use(router.routes());
app.listen(3000, async () => {console.log('Server is running at http://localhost:3000');
})