重新封装了一下NODE-MONGO 使其成为一个独立的服务.可以直接通过get/post来操作
# 重新封裝了一下NODE-MONGO 使其成為一個(gè)獨(dú)立的服務(wù).可以直接通過(guò)get/post來(lái)操作
# consts.js 配置用的數(shù)據(jù),用于全局參數(shù)配置
# log.js 自己寫(xiě)的一個(gè)簡(jiǎn)單的存儲(chǔ)本地log的功能,數(shù)據(jù)庫(kù)異常或者邏輯上產(chǎn)生異常數(shù)據(jù)的時(shí)候輸出查錯(cuò)
# servicemongo.js 主服務(wù)程序,可以直接node servicemongo.js 啟動(dòng),掛起端口服務(wù)
# routemongo.js 請(qǐng)求路由相關(guān)
# mongo.js 封裝了一些基本的node對(duì)mongo操作
# 使用方法,直接node ?servicemongo.js 就行,也可以在另一個(gè)項(xiàng)目里調(diào)用servicemongo的start?
# 注意 node包沒(méi)傳,缺什么自己安裝什么吧,看下錯(cuò)誤日志,缺什么就直接npm i XXX 裝上就好
項(xiàng)目我打包上傳到資源了(待審核狀態(tài),差不多明天就能下載了):
https://me.csdn.net/download/u013761036
consts.js
log.js
var fs = require('fs'); const sd = require('silly-datetime');//輸出log的時(shí)候,可以傳過(guò)來(lái)一個(gè)key,來(lái)代表這個(gè)是誰(shuí)輸出的,建議是文件名字+函數(shù)名字 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';// 創(chuàng)建一個(gè)可以寫(xiě)入的流,寫(xiě)入到文件 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("寫(xiě)入完成。");});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) => {//數(shù)據(jù)庫(kù)操作失敗一定全都打log出來(lái)。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(); }//查詢數(shù)據(jù),條件查詢,但是不支持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; }//查詢數(shù)據(jù),value專門(mén)支持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; }//根據(jù)條件刪除數(shù)據(jù),不支持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; }//插入一條數(shù)據(jù) 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);//自動(dòng)添加創(chuàng)建時(shí)間和修改時(shí)間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 == '') {//過(guò)濾掉這種,防止后面誤操作破壞數(shù)據(jù)庫(kù)數(shù)據(jù)return res.end();}let postdataobj = null;try {postdataobj = querystring.parse(postdata);} catch (e) {let logMess = 'Mongo operation failed:\n' + JSON.stringify(params) + '\npostdata:' + postdataconsolelog('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();?
總結(jié)
以上是生活随笔為你收集整理的重新封装了一下NODE-MONGO 使其成为一个独立的服务.可以直接通过get/post来操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: node-mongo-服务器封装
- 下一篇: Docker安装和helloworld