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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/250480.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java Web 请求转发与请求重定向

Java Web 请求转发与请求重定向 请求转发 服务器行为,即用户向服务器发送了一次http请求,该请求可能会经过多个信息资源处理以后菜返回给用户,各个信息资源使用请求转发机制互相转发请求,但是用户是感觉不到请求转发的。通过req…

05.RDD详解

05.Spark--RDD详解 RDD详解--groupByKey--reduceByKey [MapPartitionRDD单词统计] 单词统计 import org.apache.spark.{SparkConf,SparkContext} object WordCountScala{def main(args:Array[String]):Unit{//创建spark配置对象val confnew SparkConf()conf.setAppName("W…

Mininet

首先,我折腾了两周多的东西终于弄出一点眉目了。 有以下几个内容需要学习记忆一下。 1.虚拟机,弄不出来共享文件夹,就用U盘吧,贼快还不用安装配置各种东西,virtualbox和VMware都支持。 2.ubantu安装软件中途失败&#…

docker --- 使用docker-compose.yml生成redis,并连接redis-cli

docker.compose.yml 配置 version: 3.1 services:redis:image: redisports:- 6379:6379命令行:docker-compose up 查看: docker ps 进入redis-cli,输入以下 docker exec -it 7dc0a redis-cli -h localhost -p 6379 操作Redis数据 设置 namemarron set name marron 获取nam…

浅谈javaweb三大框架和MVC设计模式

浅谈javaweb三大框架和MVC设计模式转载自:http://blog.csdn.net/sunpeng19960715/article/details/50890705 小序:博主以前在学javaweb的时候开始总不理解javaweb三大框架和MVC框架模式,虽然没有把两者混为一谈,但是也是很晕菜。…

win下配置nginx

1.下载:http://nginx.org/en/download.html 2.在安装目录cmd: start nginx.exe 启动nginx 3.修改默认运行端口80(nginx.conf): HTTP 数据分发 修改配置文件nginx.conf相应节点: 修改完后重启服务: nginx -s reload TCP 数据分发: nginx 1.9以上版本支持tcp转发 配置文件中增加:…

在springBoot中配置web.xml中配置的servlet

第一种 web.xml (截取的需要转换的) 当拦截到 /socke t时执行该servlet <servlet><servlet-name>websocket</servlet-name><servlet-class>org.ldd.ssm.hangyu.socket.MyWebSocketServlet</servlet-class></servlet><servlet-mapping&g…

koa --- koa-bouncer验证

使用 koa-bouncer中间件对传入的数据进行验证 const bouncer require(koa-bouncer); app.use(bouncer.middleware());const val async (ctx, next) > {ctx.validateBody(name).required(要求提供用户名).isLength(6, 16, 用户名长度应该为6~16).isString().trim()next();…

static关键字的作用

//C/C程序员面试指南 杨国祥等编著 定义全局静态变量。全局静态变量有以下特点&#xff1a; 在全局数据区分配内存&#xff1b;如果没有初始化&#xff0c;其默认值为0&#xff1b;该变量在本文件内从定义开始到文件结束可见。定义局部静态变量。局部静态变量有以下特点&…

Redis 初次尝试

Redis 初次尝试 第一次接触redis&#xff0c;也不知道要写些什么。就玩了下将redis列表中的数据存入mysql数据库中。 首先有三个文件&#xff1a; redis.php 添加数据进redis&#xff1b; insert_class.php 将数据插入数据库&#xff1b; inert.php 调用insert_class.php;…

fiddler2抓包数据工具使用教程

一款免费且功能强大的数据包抓取软件。它通过代理的方式获取程序http通讯的数据&#xff0c;可以用其检测网页和服务器的交互情况&#xff0c;能够记录所有客户端和服务器间的http请求&#xff0c;支持监视、设置断点、甚至修改输入输出数据等功能。fiddler包含了一个强大的基于…

egg --- 初始化一个egg项目基本结构说明

Egg.js体验 全局安装 // 创建项目 $ npm i egg-init -g $ egg-init egg-example --typesimple $ cd egg-example $ npm i// 启动项目 $ npm run dev $ open localhost:7000Egg.js的结构 路由(Router): 将请求URL和具体承担执行动作的Controller的关系对应控制器(Controller)…

葫芦娃

葫芦娃救爷爷 1.队名——代码那些事儿 2.团队成员 刘佳 211606320&#xff08;队长&#xff09;李佳 211660313周世元 211606348王浩 211606378曾丽丽 211606302陈水莲 211606303许燕婷 211606338杨小妮 2116063413.队长博客链接 -https://www.cnblogs.com/LJ-D/p/9799944.html…

webstorm遇到的问题

问题一&#xff1a;英译&#xff1a;未指定node.js的解释器。 解决方法&#xff1a;将webstorm配置支持node.js并自动补全 步骤&#xff1a; 先下载node.jsFile->Setting->输入Node.js&#xff08;选中点进去&#xff09;->Node imterpreter&#xff08;选择node的安装…

egg --- 配置连接mysql 创建模型 插入数据

在egg中使用egg-sequelize插件 sequelize是与数据库操作相关的库安装: npm install --save egg-sequelize mysql2 在egg中配置sequelize 1.在 config/plugin.js中引入 egg-sequelize插件,代码如下 sequelize: {enable: true,package: egg-sequelize }2.在config/config.def…

Flask 在 Debug 模式下初始化2次

请移步&#xff1a; http://blog.zengrong.net/post/2632.html https://stackoverflow.com/questions/9449101/how-to-stop-flask-from-initialising-twice-in-debug-mode/9476701#9476701 https://stackoverflow.com/questions/25504149/why-does-running-the-flask-dev-serve…

eclipse报错: Could not generate secret

在调用微信接口时&#xff0c;出现一个错误&#xff1a; 一直以为是接口调用问题&#xff0c;经多方查询和尝试解决&#xff0c;最后找到根源&#xff1a; edit-->使用default就可以了。 原因&#xff1a; 在eclipse中运行时&#xff0c;把签名信息给去掉了。 转载于:https:…

koa --- [MVC实现之一]自定义路由读取规则

实现MVC分层架构 目标是创建约定大于配置、开发效率高、可维护性强的项目架构路由处理 规范 所有路由,都要放在routes文件夹中若导出路由对象,使用 动词空格路径 作为key, 值是操作方法若导出函数, 则函数返回第二条约定格式的对象 路由定义: 新建 router/index.js, 默认index…

sql中的left join、right join、inner join

sql中的left join、right join、inner join 转自&#xff1a;http://www.cnblogs.com/pcjim/articles/799302.html left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录 right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录inner join…

bzoj1128 Lam-lights

题目描述 对于一个长度为n的数列p&#xff0c;数列中任意两个数互质。准备一个无限长的储存器。然后从p1开始&#xff0c;把储存器中p1倍数位置都赋值为p1&#xff0c;把储存器中p2倍数位置都赋值为p2&#xff0c;把储存器中p3倍数位置都赋值为p3。。。把储存器中pn倍数位置都赋…