日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

koa --- mongoose连接mongoDB

發布時間:2023/12/10 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 koa --- mongoose连接mongoDB 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用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'); })

總結

以上是生活随笔為你收集整理的koa --- mongoose连接mongoDB的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。