node-mongo封装

node 里面调用mongo封装了下。

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






测试调用文件
const mongo = require('./mongo');
const { ObjectId } = require('mongodb');
const _ = require('lodash');

const main = async () => {
  // const datas =  mongo.findMongo("data", "wck", {"_id" : ObjectId("59e05df004fe65001b841ec7")});
  // console.log(datas);

  // const datas =  mongo.updateMongo("data", "wck", {"_id" : ObjectId("59e05df004fe65001b841ec7")}, {contact:'cc'});
  // console.log(datas);

  // const datas =  mongo.insertMongo("data", "wck", [{x:'x'},{y:'y'},{z:'z'}]);
  // console.log(datas);

  // const datas =  mongo.deleteMongo("data", "wck", { "x": "x", "_id": ObjectId("5d91d0d5c5701e074d4174ed") });
  // console.log(datas);
}

main();



可以在上面的基础上继续封装,然后把mongo数据数据库单独挂在一个服务器上或者是docker镜像上,通过url get put post 等方式访问更新操作。目前我正在封装这个,接口类似:
http://127.0.0.1:2323/?k=q&n=data&c=wck&w={"y":"y"}
注意安全问题,比如锁死ip。



 

你可能感兴趣的:(数据库)