【mongo】使用node创建接口,查询mongo,返回结果在接口中(2/3)

1. 初始化一些测试数据,清空原有的数据并插入100条测试数据
node initData.js
initData.js
const mongodb = require('./models/db');
mongodb.once('connect', async () => {
    const col = mongodb.col('fruits');
    // 删除已存在的数据
    await col.deleteMany();
    const data = new Array(100).fill().map((value, index) => {
        return {
            name: 'XXXX' + index,
            price: index,
            category: Math.random() > 0.5 ? '蔬菜' : '水果',
        }
    })
   
    // 插入新建的数据
    await col.insertMany(data);
    console.log('插入测试数据成功');
})
models/db.js
const conf = require('./conf');
const { EventEmitter } = require('events');   // 数据库异步连接工具

// 客户端
const { MongoClient } = require('mongodb');
class Mongodb {
    constructor(conf) {
        this.conf = conf;
        this.emmiter = new EventEmitter();
        // 连接
        this.client = new MongoClient(conf.url, {
            useNewUrlParser: true,
        })

        this.client.connect(err => {
            console.log(err);
            if (err) {
                throw err;
            }
            console.log('连接正常');
            this.emmiter.emit('connect')
        })
    }
    col(colName, dbName = conf.dbName) {
        return this.client.db(dbName).collection(colName);
    }

    once(event, cb) {
        this.emmiter.once(event, cb)
    }
}
module.exports = new Mongodb(conf)
models/conf.js
module.exports = {
    url: 'mongodb://127.0.0.1:27017',
    dbName: 'local',
}
2. 对外接口

使用http://localhost:3000/api/list?keyword=20访问接口,并传参pageNum、pageSize、category、keyword查询

node search.js
search.js
const express = require('express');
const app = express();
const path = require('path');
const mongo = require('./models/db');

app.get('/api/list', async (req, res) => {
    // 分页查询
    const {pageNum, pageSize, category, keyword} = req.query;
    let size = Number(pageSize || 5);
    try {
       
        // 构建查询条件
        const condition = {};
        if (category) {
            condition.category = category;
        }
        if (keyword) {
            condition.name = {$regex: new RegExp(keyword)}
        }

        const col = mongo.col('fruits');
        const total = await col.find(condition).count();
        const fruits = await col.find(condition)
            .skip((pageNum - 1) * size)
            .limit(size)
            .toArray();
        res.json({
            code: 1,
            data: {
                fruits: fruits,
                page: {
                    total: total,
                }
            }
        })
    } catch (error) {
        console.log(error)
    }
})

app.get('/api/category', async (req, res) => {
    const col = mongo.col('fruits');
    const data = await col.distinct('category');
    res.json({
        code: 1,
        data: data,
    })
})
app.listen(3000);

你可能感兴趣的:(node.js,mongodb)