node-mongo-服务器封装

分为三个文件
mongo.js基本的封装了下mongo数据库操作
workmongo.js 里面有路由和解析操作(可以根据具体业务进行扩充)
mainmongo.js 服务器相关

调用例子:

查询数据
http://127.0.0.1:2323/get?k=q&n=data&c=wck&w={"y":"y"}
添加数据
http://127.0.0.1:2323/post?k=i&n=data&c=wck 具体的内容,在post的body里面,采用标准json格式就好

----------------------------------------------------
mongo.js
const { MongoClient, ObjectId } = require('mongodb');
const mongourl = "mongodb://localhost:27017/";

const findMongo = (dbname, collection, where, req, res) => {
    MongoClient.connect(mongourl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
        if (err) throw err;
        const db = client.db(dbname);
        db.collection(collection).find(where).sort({ uptime: -1 }).toArray(function (err, datas) {
            if (err) throw err;
            res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
            res.end(JSON.stringify(datas));
            //client.close();
        });
    });
    return;
}

const insertMongo = async (dbname, collection, newdatas, req, res) => {

    MongoClient.connect(mongourl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
        if (err) throw err;
        const db = client.db(dbname);
        db.collection(collection).insertMany(newdatas, function (err, datas) {
            if (err) throw err;
            res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
            res.end(JSON.stringify(datas));
            //client.close();
        });
    });
    return;
}

module.exports = {
    findMongo,
    insertMongo
};




----------------------------------------------------
workmongo.js
const url = require('url');
const mongo = require('./mongo');
const querystring = require('querystring');

//get 获取数据/查询
const work_get = async (req, res) => {
    const params = url.parse(req.url, true).query;
    try {
        switch (params.k) {
            case 'q': {
                if (params.n && params.c) {
                    //基本查询 条件里不能加 ObjectId 如果需要的话可以单独写
                    //dbname collection where
                    //http://127.0.0.1:2323/get?k=q&n=data&c=wck&w={"y":"y"}
                    mongo.findMongo(params.n, params.c, JSON.parse(params.w), req, res);
                }
            } break;
            default: {
                res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
                res.write("Wow");
                res.end();
            }; break;
        }
    } catch (e) {
        datas = null;
    }
}

//post 创建数据
const work_post = async (req, res) => {
    const params = url.parse(req.url, true).query;
    let postdata = '';
    req.on('data', function (chunk) {
        postdata += chunk;
    });
    req.on('end', async function () {
        postdataobj = querystring.parse(postdata);
        try {
            switch (params.k) {
                case 'i': {
                    if (params.n && params.c) {
                        //插入一条数据
                        //dbname collection where
                        //http://127.0.0.1:2323/post?k=i&n=data&c=wck 具体的内容,在post的body里面,采用标准json格式就好
                        const postdataobjarr = [postdataobj];
                        mongo.insertMongo(params.n, params.c, postdataobjarr, req, res);
                    }
                } break;
                default:{
                    res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
                    res.write("Wow");
                    res.end();
                }; break;
            }
        } catch (e) {
            datas = null;
        }
    });
}

//其他的各种增删改查 就按照上面的思路 再结合具体业务场景 慢慢写就好。
//建议 表转化 查询用 get 增加用 post 更改用 put 删除的话随意把。
//注意url的最大长度问题。

module.exports = {
    work_get,
    work_post
};


----------------------------------------------------
mainmongo.js
const http = require('http');
var url = require("url");
const workmongo = require('./workmongo');

const route = async (req, res) => {
    //console.log("url.pathname:" + url.parse(req.url).pathname);
    switch (url.parse(req.url).pathname) {
        case "/get": {
            workmongo.work_get(req, res);
        }; break;
        case "/post": {
            workmongo.work_post(req, res);
        }; break;
        default: {
            res.end();
        } break;
    }
}

const main = async () => {
    http.createServer(function (req, res) {
        route(req, res);

    }).listen(2323);
};

main();





原文地址:https://www.cnblogs.com/csnd/p/12061851.html