天天看点

koa --- > mongoose连接mongoDB使用Mongoose对MongoDB进行操作Mongoose中的Schema栗子

使用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 = 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(()=>{

})
           

栗子

  • 目录结构如下
    koa --- > mongoose连接mongoDB使用Mongoose对MongoDB进行操作Mongoose中的Schema栗子
  • 说明:

    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 笔记