最近在用MongoDB➕Koa2做个小项目,记录一下:
首先,如何连接线上数据库:
const url = `mongodb://user:pwd@ipaddr:27017/Blog`; const monk = require('monk'); const db = monk(url); db.then(() => { console.log('MongoDB数据库连接成功!') }) module.exports = db;
实际操作:
模糊查询
通过$regex来实现
const query = { name: { $regex: new RegExp(name) } };
获取查询出来的总数量,分页
const count = await tagsCol.count(query); let list = await tagsCol.find(query, { projection: { _id: 0 }, ...new ctx.MongoQuery.Pagination(page, size), });
MongoQuery.js
var Pagination = require('./Pagination'); function MongoQuery() { } MongoQuery.Pagination = Pagination; module.exports = () => async (ctx, next) => { ctx.MongoQuery = MongoQuery; await next(); }
字段筛选
// 0 就是不显示,1就是显示 projection: { _id: 0 },
整体代码如下:
const router = require('koa-router')() const db = require('../db'); const tagsCol = db.get('tags') router.prefix('/tags') /** * @ / 查询列表分页 * @ /insert 新增数据 * @ /update 修改数据 * @ /drop 删除数据 * @ /all 查询所有数据 */ router.get('/', async (ctx, next) => { const { name, page, size } = ctx.query; const query = { name: { $regex: new RegExp(name) } }; try { const count = await tagsCol.count(query); let list = await tagsCol.find(query, { projection: { _id: 0 }, ...new ctx.MongoQuery.Pagination(page, size), }); ctx.body = new ctx.JsonResponse(200, { list, count }) } catch (e) { ctx.body = new ctx.JsonResponse(500, {}) } db.close(); }); router.get('/insert', async (ctx, next) => { ctx.body = '插入成功!'; }); router.post('/update', async (ctx, next) => { ctx.body = 'this is a users/bar response' }); router.get('/drop', async (ctx, next) => { const { id } = ctx.query; try { await tagsCol.remove({ id: Number(id) }); ctx.body = new ctx.JsonResponse(200) } catch (e) { ctx.body = new ctx.JsonResponse(500) } db.close(); }); module.exports = router