# 重新封装了一下NODE-MONGO 使其成为一个独立的服务.可以直接通过get/post来操作

# consts.js 配置用的数据,用于全局参数配置

# log.js 自己写的一个简单的存储本地log的功能,数据库异常或者逻辑上产生异常数据的时候输出查错

# servicemongo.js 主服务程序,可以直接node servicemongo.js 启动,挂起端口服务

# routemongo.js 请求路由相关

# mongo.js 封装了一些基本的node对mongo操作

# 使用方法,直接node  servicemongo.js 就行,也可以在另一个项目里调用servicemongo的start 

# 注意 node包没传,缺什么自己安装什么吧,看下错误日志,缺什么就直接npm i XXX 装上就好

项目我打包上传到资源了(待审核状态,差不多明天就能下载了):

https://me.csdn.net/download/u013761036

consts.js

module.exports = {
default: {
defaultDataServicePort: 2323,//数据库服务接口端口
defaultMongoUrl : 'mongodb://localhost:27017/',//Mongo数据库连接地址
}
}

log.js

var fs = require('fs');
const sd = require('silly-datetime'); //输出log的时候,可以传过来一个key,来代表这个是谁输出的,建议是文件名字+函数名字 xxx.js-funxx
//consolelog('main.js-main', 'star-ok');
function consolelog(key, data) {
try {
if ('string' != typeof data) {
data = JSON.stringify(data);
}
let formatData = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss') + '->' + key + '\n';
formatData = formatData + data + '\n\n';
// 创建一个可以写入的流,写入到文件 xxx-xx-xx.log 中,日期
let outPutLogFilePath = "./" + sd.format(new Date(), 'YYYY-MM-DD') + ".log";
var writerStream = fs.createWriteStream(outPutLogFilePath, { 'flags': 'a' });
writerStream.write(formatData, 'UTF8');
writerStream.end();
writerStream.on('finish', function () {
//console.log("写入完成。");
});
writerStream.on('error', function (err) {
//console.log(err.stack);
});
} catch (e) { }
}
module.exports = {
consolelog,
};

mongo.js

const url = require('url');
const { MongoClient, ObjectId } = require('mongodb');
const sd = require('silly-datetime');
const _ = require('lodash');
const { consolelog } = require('./log');
const config = require('./consts');
const { defaultMongoUrl: mongourl } = _.get(config, 'defaultMongoUrl', config.default); const goError = (mongoLink, req, res, body = null) => {
//数据库操作失败一定全都打log出来。
const params = url.parse(req.url, true).query;
let logMess = 'Mongo operation failed:' + JSON.stringify(params);
if (body) {
logMess = logMess + '\nBody:' + JSON.stringify(body);
}
consolelog('mongo.js-goError', logMess);
if (mongoLink != null) {
mongoLink.close();
}
res.end();
} //查询数据,条件查询,但是不支持ObjectID,条件的格式是{"key":"value"}
const findMongo = (dbname, collection, where, req, res) => {
MongoClient.connect(mongourl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
//if (err) throw err;
if (err) {
return goError(client, req, res);
}
try {
where = JSON.parse(where);
} catch (e) {
return goError(client, req, res);
}
const db = client.db(dbname);
db.collection(collection).find(where).sort({ updateTime: -1 }).toArray(function (err, datas) {
//if (err) throw err;
if (err) {
return goError(client, req, res);
}
res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
res.end(JSON.stringify(datas));
client.close();
});
});
return;
} //查询数据,value专门支持ObjectID类型,key可以是_id,也可以是别的
const findMongoByKOBJV = (dbname, collection, key, value, req, res) => {
MongoClient.connect(mongourl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
//if (err) throw err;
if (err) {
return goError(client, req, res);
}
const db = client.db(dbname);
const were = {};
try {
were[key] = ObjectId(value);
} catch (e) {
return goError(client, req, res);
}
db.collection(collection).find(were).sort({ updateTime: -1 }).toArray(function (err, datas) {
//if (err) throw err;
if (err) {
return goError(client, req, res);
}
res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
res.end(JSON.stringify(datas));
client.close();
});
});
return;
} //根据条件删除数据,不支持ObjectID类型
const deleteMongo = (dbname, collection, body, req, res) => {
MongoClient.connect(mongourl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
//if (err) throw err;
if (err) {
return goError(client, req, res, body);
}
const db = client.db(dbname);
if (body.were == null) {//卡一下,防止出人命!
return goError(client, req, res, body);
}
let were = null;
try {
were = JSON.parse(body.were);
} catch (e) {
return goError(client, req, res, body);
}
db.collection(collection).deleteMany(were, function (err, datas) {
//if (err) throw err;
if (err) {
return goError(client, req, res, body);
}
res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
//{"result":{"n":0,"ok":1},"connection":{"id":6,"host":"localhost","port":27017},"deletedCount":0,"n":0,"ok":1}
res.end(JSON.stringify(datas));
client.close();
});
});
return;
} const deleteMongoByKOBJV = (dbname, collection, body, req, res) => { MongoClient.connect(mongourl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
//if (err) throw err;
if (err) {
return goError(client, req, res, body);
}
const db = client.db(dbname);
let key = body.key;
let value = body.value;
if ((!key) || (!value)) {//卡一下,防止出人命!
return goError(client, req, res, body);
}
let were = {};
try {
were[key] = ObjectId(value);
} catch (e) {
return goError(client, req, res, body);
} db.collection(collection).deleteMany(were, function (err, datas) {
//if (err) throw err;
if (err) {
return goError(client, req, res, body);
}
res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
//{"result":{"n":0,"ok":1},"connection":{"id":4,"host":"localhost","port":27017},"deletedCount":0,"n":0,"ok":1}
res.end(JSON.stringify(datas));
client.close();
});
});
return;
} //插入一条数据
const insertMongo = (dbname, collection, body, req, res) => {
MongoClient.connect(mongourl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
//if (err) throw err;
if (err) {
return goError(client, req, res, body);
}
let db = client.db(dbname);
//自动添加创建时间和修改时间
body[0]['createdAt'] = new Date();
body[0]['updatedAt'] = new Date();
db.collection(collection).insertMany(body, function (err, datas) {
//if (err) throw err;
if (err) {
return goError(client, req, res, body);
}
res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
//{"result":{"ok":1,"n":1},"ops":[{"v1":"1111","v2":"2222","createdAt":"2019-11-05T08:07:37.087Z","updatedAt":"2019-11-05T08:07:37.087Z","_id":"5dc12dc99af00a30429a4b5c"}],"insertedCount":1,"insertedIds":{"0":"5dc12dc99af00a30429a4b5c"}}
res.end(JSON.stringify(datas));
client.close();
});
});
return;
} const updateById = (dbname, collection, body, req, res) => { MongoClient.connect(mongourl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
//if (err) throw err;
if (err) {
return goError(client, req, res, body);
}
let db = client.db(dbname);
let _id = null;
let updata = null;
try {
_id = ObjectId(body.id);
updata = JSON.parse(body.data);
updata['updatedAt'] = new Date();
} catch (e) {
return goError(client, req, res, body);
}
let updateCmd = { $set: updata };
db.collection(collection).updateOne({ _id }, updateCmd, function (err, datas) {
//if (err) throw err;
if (err) {
return goError(client, req, res, body);
}
res.writeHead(200, { "Content-Type": "text/plain; charset=utf8" });
//{"result":{"n":1,"nModified":1,"ok":1},"connection":{"id":2,"host":"localhost","port":27017},"modifiedCount":1,"upsertedId":null,"upsertedCount":0,"matchedCount":1,"n":1,"nModified":1,"ok":1}
res.end(JSON.stringify(datas));
client.close();
});
});
return;
} module.exports = {
updateById,
findMongoByKOBJV,
deleteMongoByKOBJV,
deleteMongo,
findMongo,
insertMongo
};

routemongo.js

const url = require('url');
const mongo = require('./mongo');
const querystring = require('querystring');
const { consolelog } = require('./log'); const workFind = async (req, res) => {
const params = url.parse(req.url, true).query;
switch (params.cmd) {
case 'query': {
mongo.findMongo(params.n, params.c, params.w, req, res);
} break;
case 'querykeyid': {
mongo.findMongoByKOBJV(params.n, params.c, params.k, params.v, req, res);
} break;
default: {
res.end();
}; break;
}
} const workUpdate = 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 () {
if (postdata == '') {//过滤掉这种,防止后面误操作破坏数据库数据
return res.end();
}
let postdataobj = null;
try {
postdataobj = querystring.parse(postdata);
} catch (e) {
let logMess = 'Mongo operation failed:\n' + JSON.stringify(params) + '\npostdata:' + postdata
consolelog('routemongo.js-workUpdate', logMess);
return res.end();
}
try {
switch (params.cmd) {
case 'delete': {
mongo.deleteMongo(params.n, params.c, postdataobj, req, res);
} break;
case 'deletekeyid': {
mongo.deleteMongoByKOBJV(params.n, params.c, postdataobj, req, res);
} break;
case 'insert': {
const postdataobjarr = [postdataobj];
mongo.insertMongo(params.n, params.c, postdataobjarr, req, res);
} break;
case 'updatebyid': {
mongo.updateById(params.n, params.c, postdataobj, req, res);
} break;
default: {
res.end();
}; break;
}
} catch (e) {
datas = null;
}
});
} module.exports = {
workFind,
workUpdate
};

servicemongo.js

const http = require('http');
var url = require("url");
const routemongo = require('./routemongo');
const config = require('./consts');
const { consolelog } = require('./log');
const _ = require('lodash'); const route = async (req, res) => {
switch (url.parse(req.url).pathname) {
case "/find": {//查
routemongo.workFind(req, res);
}; break;
case "/update": {//增 删 改
routemongo.workUpdate(req, res);
}; break;
default: {
res.end();
} break;
}
} const start = async () => {
const { defaultDataServicePort } = _.get(config, 'defaultDataServicePort', config.default);
consolelog('servicemongo.js-start', 'start:' + defaultDataServicePort);
http.createServer(function (req, res) {
route(req, res);
}).listen(defaultDataServicePort);
}; module.exports = {
start,
}; start();

重新封装了一下NODE-MONGO 使其成为一个独立的服务.可以直接通过get/post来操作的更多相关文章

  1. 【node】用koa搭建一个增删改服务(一)

    前文,vue分类里有一个日志demo的练习,这篇文章就是介绍针对日志demo的服务是怎么写的 一.koa搭建项目 1. npm init 2. npm install koa 二.建数据库 下面是项目 ...

  2. Node.js的cluster模块——Web后端多进程服务

    众所周知,Node.js是单线程的,一个单独的Node.js进程无法充分利用多核.Node.js从v0.6.0开始,新增cluster模块,让Node.js开发Web服务时,很方便的做到充分利用多核机 ...

  3. ytu 1050:写一个函数,使给定的一个二维数组(3×3)转置,即行列互换(水题)

    1050: 写一个函数,使给定的一个二维数组(3×3)转置,即行列互换 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 154  Solved: 112[ ...

  4. 前端使用node.js的http-server开启一个本地服务器

    前端使用node.js的http-server开启一个本地服务器 在写前端页面中,经常会在浏览器运行HTML页面,从本地文件夹中直接打开的一般都是file协议,当代码中存在http或https的链接时 ...

  5. npm 是node.js下带的一个包管理工具

    npm 是node.js下带的一个包管理工具          npm install -g webpack webpack是一个打包工具 gulp是一个基于流的构建工具,相对其他构件工具来说,更简洁 ...

  6. 用node.js从零开始去写一个简单的爬虫

    如果你不会Python语言,正好又是一个node.js小白,看完这篇文章之后,一定会觉得受益匪浅,感受到自己又新get到了一门技能,如何用node.js从零开始去写一个简单的爬虫,十分钟时间就能搞定, ...

  7. es6模板字符串使用使${} 来包裹一个变量或者一个表达式

    es6模板字符串使用使${} 来包裹一个变量或者一个表达式 2019-04-28 14:33:54 Gabriel_wei 阅读数 1774  收藏 更多 分类专栏: 前端   版权声明:本文为博主原 ...

  8. k8s 使本地集群支持 LoadBalancer 服务

    k8s 使本地集群支持 LoadBalancer 服务 为了使本地集群支持 LoadBalancer 服务,可以参考以下两种实现方案: keepalived-cloud-provider metalL ...

  9. Codeforces Round #304 (Div. 2) B. Soldier and Badges【思维/给你一个序列,每次操作你可以对一个元素加1,问最少经过多少次操作,才能使所有元素互不相同】

    B. Soldier and Badges time limit per test 3 seconds memory limit per test 256 megabytes input standa ...

随机推荐

  1. 掌握HTTP原理

    URI和URL URI的全程为Uniform Resource identifier,即统一资源标志符,URL的全称 Universal Resource Locator 即统一资源定位符 在目前的互 ...

  2. 翻译:《实用的Python编程》04_03_Special_methods

    目录 | 上一节 (4.2 继承) | 下一节 (4.4 异常) 4.3 特殊方法 可以通过特殊方法(或者称为"魔术"方法(magic method))自定义 Python 行为的 ...

  3. 关于Java中Collections.sort和Arrays.sort的稳定性问题

    一 问题的提出   关于Java中Collections.sort和Arrays.sort的使用,需要注意的是,在本文中,比较的只有Collections.sort(List<T> ele ...

  4. Spring源码之ApplicationContext

    ​ 本文是针对Srping的ClassPathXMLApplicationContext来进行源码解析,在本篇博客中将不会讲述spring Xml解析注册代码,因为ApplicationContext ...

  5. 「HTML+CSS」--自定义按钮样式【002】

    前言 Hello!小伙伴! 首先非常感谢您阅读海轰的文章,倘若文中有错误的地方,欢迎您指出- 哈哈 自我介绍一下 昵称:海轰 标签:程序猿一只|C++选手|学生 简介:因C语言结识编程,随后转入计算机 ...

  6. java例题_47 读取 7 个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*

    1 /*47 [程序 47 打印星号] 2 题目:读取 7 个数(1-50)的整数值,每读取一个值,程序打印出该值个数的*. 3 */ 4 5 /*分析 6 * 1.多次读取---for循环 7 * ...

  7. java例题_24 逆向输入数字

    1 /*24 [程序 24 根据输入求输出] 2 题目:给一个不多于 5 位的正整数,要求:一.求它是几位数,二.逆序打印出各位数字. 3 */ 4 5 /*分析 6 * 首先从键盘得到一个正整数,不 ...

  8. .Net Core 3.1浏览器后端服务(五) 引入定时任务Quartz.Net

    一.前言 近期项目中遇到一些需求,需要定时写入数据库,定时刷新缓存的问题,因此需要引入任务调度机制. 我的选择是使用 Quartz.Net,使用的版本是 3.2.4 这里强调一点:3.x的版本与2.x ...

  9. Python | random 模块:Python 中如何生成随机数和随机抽样?

    random 是平时开发过程中常用的一个模块,该模块实现了各种分布的伪随机数生成器,以及和随机数相关的各种实用函数.基本函数 random() 在区间 [0.0, 1.0) 内均匀生成随机浮点数,是模 ...

  10. 使用 docker 进行 ElasticSearch + Kibana 集群搭建

    在Docker容器中运行Elasticsearch Kibana和Cerebro 机器信息 10.160.13.139 10.160.9.162 10.160.11.171 1. 安装docker和d ...