zoukankan      html  css  js  c++  java
  • 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。
    
    
    
    
  • 相关阅读:
    OLAP ODS项目的总结 平台选型,架构确定
    ORACLE ORA12520
    ORACLE管道函数
    ORACLE RAC JDBC 配置
    ORACLE RAC OCFS连接产生的错误
    ORACLE 启动和关闭详解
    OLAP ODS项目的总结 起步阶段
    ORACLE RAC 配置更改IP
    ORACLE RAC OCR cann't Access
    ORACLE RAC Debug 之路 CRS0184错误与CRS初始化
  • 原文地址:https://www.cnblogs.com/csnd/p/12061852.html
Copyright © 2011-2022 走看看