关于node.js:使用node创建接口查询mongo返回结果在接口中

34次阅读

共计 1878 个字符,预计需要花费 5 分钟才能阅读完成。

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);

正文完
 0