Mongodb入門5
阿新 • • 發佈:2021-08-09
最近在用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