1.根目錄/module/db.jsjavascript
/** * DB庫 */ var MongoClient = require('mongodb').MongoClient; var Config = require('./config.js'); class Db { /** * 單例 * 解決屢次實例化,實例不共享的問題 */ static getInstance() { if (!Db.instance) { Db.instance = new Db(); } return Db.instance; } constructor() { this.dbClient = ''; /*屬性 存放db對象*/ this.connect(); /*實例化的時候就鏈接數據庫*/ } connect() { /*鏈接數據庫*/ let _that = this; return new Promise((resolve, reject) => { if (!_that.dbClient) { /*解決數據庫屢次鏈接的問題*/ MongoClient.connect(Config.dbUrl, (err, client) => { if (err) { reject(err); } else { _that.dbClient = client.db(Config.dbName); resolve(_that.dbClient); } }) } else { resolve(_that.dbClient); } }) } find(collectionName, json) { /*查詢數據*/ return new Promise((resolve, reject) => { this.connect().then((db) => { var result = db.collection(collectionName).find(json); result.toArray((err, docs) => { if (err) { reject(err); return; } resolve(docs); }) }) }) } update(collectionName, json1, json2) { /*更新數據*/ return new Promise((resolve, reject) => { this.connect().then((db) => { db.collection(collectionName).updateOne(json1, { $set: json2 }, (err, result) => { if (err) { reject(err); } else { resolve(result); } }) }) }) } insert(collectionName, json) { /*新增數據*/ return new Promise((resolve, reject) => { this.connect().then((db) => { db.collection(collectionName).insertOne(json, function (err, result) { if (err) { reject(err); } else { resolve(result); } }) }) }) } remove(collectionName, json) { /*刪除數據*/ return new Promise((resolve, reject) => { this.connect().then((db) => { db.collection(collectionName).removeOne(json, function (err, result) { if (err) { reject(err); } else { resolve(result); } }) }) }) } } module.exports = Db.getInstance();
.java