[Mongo] create an interface with node, query Mongo, and return the result in the interface (2 / 3)

Time:2021-1-12
1. Initialize some test data, clear the original data and insert 100 test data
node initData.js

initData.js

const mongodb = require('./models/db');
mongodb.once('connect', async () => {
    const col = mongodb.col('fruits');
    //Delete existing data
    await col.deleteMany();
    const data = new Array(100).fill().map((value, index) => {
        return {
            name: 'XXXX' + index,
            price: index,
            category:  Math.random () > 0.5? 'vegetable':'fruit ',
        }
    })
   
    //Insert new data
    await col.insertMany(data);
    console.log ('Insert test data successfully ');
})

models/db.js

const conf = require('./conf');
Const {EventEmitter} = require ('events'); // database asynchronous connection tool

//Client
const { MongoClient } = require('mongodb');
class Mongodb {
    constructor(conf) {
        this.conf = conf;
        this.emmiter = new EventEmitter();
        //Connection
        this.client = new MongoClient(conf.url, {
            useNewUrlParser: true,
        })

        this.client.connect(err => {
            console.log(err);
            if (err) {
                throw err;
            }
            console.log ('normal connection ');
            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. External interface

usehttp://localhost: 3000 / API / list? Keyword = 20 to access the interface and transfer the parameters pagenum, PageSize, category and keyword to query

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) => {
    //Paging query
    const {pageNum, pageSize, category, keyword} = req.query;
    let size = Number(pageSize || 5);
    try {
       
        //Building query criteria
        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);