使用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相关推荐

  1. node --- 使用mongoose连接mongoDB,并初始化所有的Schema

    写了一个init.js函数 使用了glob来对协助完成(https://github.com/isaacs/node-glob) 连接的数据库的名称(smile-vue) 连接数据库操作:connec ...

  2. mongoose操作mongodb

    http://mongoosejs.com/docs/api.html#index-js mongoose是nodejs环境下操作mongodb的模块封装,使用mongoose之后,实际上只需要在mo ...

  3. koa+mongoose基础入门

    1.mongoose基本使用 1.安装mongodb npm install mongodb 2.引入mongodb数据表,连接mongodb,通过node来对mongodb进行异步的增删改查 con ...

  4. node --- 模块化连接MongoDB数据库的参数设置方案之一

    数据库的初始化操作 连接的数据库的名称 包含连接数据库 初始化所有的Schemas 暴露给其他页面使用的接口 假设写在 database/init.js 中 const mongoose = requ ...

  5. Node.js使用mongoose操作mongodb

    软件配置: 1.node v8.9.3 2. npm 5.5.1 3. mongoose及MongoDB版本见下package.json // package.json {   "name& ...

  6. Egg 中结合Mongoose操作MongoDB

    1. 安装模块 npm i egg-mongoose --save 2. 配置 egg-mongoose 插件 // config/plugin.js 'use strict'; exports.ej ...

  7. java连接mongodb_java连接mongodb源码解读

    用mongdb也大半年了,一直是业务上的逻辑实现了就ok.然而这样并不能进步--因此今天查了查java连接mongodb驱动的源码,搜到的各种信息整合一下,方便以后深入的使用. 先贴连接数据库代码Li ...

  8. python mongodb orm_Django 通过 mongoengine 连接 MongoDB 进而使用orm进行CRUD

    一. 在python脚本中, 我们通常可以使用pymongo模块实现与mongodb数据库的交互, 但是在使用Django框架进行定制开发的web server 项目中, 仍然使用pymongo模块的 ...

  9. C# 驱动连接 MongoDB ReplSet

    前言 接上一篇:MongoDB 复制集(Replica Set) 配置(Windows 版) 当配置好 MongoDB 的复制集(Replica Set)之后,肯定要做的就是应用程序连接 MongoD ...

最新文章

  1. 粒子滤波 应用_如何使用NativeScript开发粒子物联网应用
  2. 180615-精度计算BigDecimal
  3. 【Linux 内核 内存管理】RCU 机制 ① ( RCU 机制简介 | RCU 机制的优势与弊端 | RCU 机制的链表应用场景 )
  4. python回归分析预测模型_Python与线性回归模型预测房价
  5. jquery中的attr()和prop()
  6. 中南大学夏令营集训营
  7. python的常量和变量_python变量和常量
  8. zabbix监控之Centos基于LNMP环境安装
  9. 2017.10.13 硬币游戏 思考记录
  10. 在服务端合并和压缩JavaScript和CSS文件[转]
  11. bugku-管理员登录-(X-forwarded-for)
  12. ./config/config_global.php,直接git config和带--global、--system的区别
  13. python访问oracle时的问题总结
  14. android某个界面横屏,iOS强制某个界面横屏的方法
  15. 批量执行newman
  16. 100套计算机毕设源码+论文 免费分享 【2020最新版】
  17. 永恒的风控:大宗商品贸易融资背后的核心风险该如何规避?
  18. 标准库之正则表达式3-前后向管理
  19. SpringBoot服务监控之Actuate
  20. 互联网界的IT巨变:从DOS的编辑器,到如今的无代码开发

热门文章

  1. java 四种内存_不可访问内存 Java四种引用包括强引用,软引用,弱引用,虚引用...
  2. 返回后的数据处理_【掘金使用技巧2】掘金返回数据中时间的处理方法
  3. freemaker if 多个条件_第4天|14天搞定Vue3.0,条件渲染和template
  4. asp mysql insert_用asp把表单数据插入数据库的2种常用方法
  5. pb9数据窗口中显示行数据与当前行区别_Hive的窗口函数
  6. 【PTVS+Theano+CPU/GPU】在windows下使用VS安装theano深度学习工具
  7. js获取页面的各种高度与宽度
  8. 王之泰201771010131《面向对象程序设计(java)》第九周学习总结
  9. Tomcat启动失败错误解决Could not publish server configuration for Tomcat v8.0 Server at localhost....
  10. Laravel日志查看器 -- log-viewer扩展