我正在编写一个模块以使用等待功能来执行mongo数据库异步操作: https://github.com/Alexander-Herranz/async-await-mongoclient-es6-promisify
async / await native语句仅适用于节点> = v8。 我想验证这是最好的方法: 1)验证只有一个与数据库的开放连接(在类DB的单个实例中)。
2)确保只执行myMongoDB.collection(collectionName)一次,并将其传递给mongo db操作。
3)mongo客户端异步/等待管理的方法(从未使用过这种方式)
//test.js
require('dotenv').config()
const {Db} = require("./db/db")
const db = new Db(process.env.DB_NAME)
testMongoAPI()
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
async function testMongoAPI() {
try {
const dbGetCol = await
db.getCollection(process.env.COLLECTION_NAME)
let query1 = {}
query1.hola=getRandomInt(1,999)
await db.insertInCollection(dbGetCol, query1)
let query2 = {}
query2.hola=getRandomInt(1,999)
query2.uno="dos"
await db.insertInCollection(dbGetCol, query2)
let query3 = {}
query3.hola=getRandomInt(1,999)
query3.uno="dos"
await db.insertInCollection(dbGetCol, query3)
let query4 = {}
query4.hola=getRandomInt(1,999)
query4.uno="dos"
await db.insertInCollection(dbGetCol, query4)
let query5 = {}
query5.hola=getRandomInt(1,999)
await db.insertInCollection(dbGetCol, query5)
let query6 = {}
query6.hola=getRandomInt(1,999)
await db.insertInCollection(dbGetCol, query6)
let query7 = {}
query7.hola=getRandomInt(1,999)
await db.insertInCollection(dbGetCol, query7)
await db.getOneFromQuery(dbGetCol, query2)
let cond1 = {}
cond1.uno="dos"
await db.getAllFromQuery(dbGetCol, cond1)
await db.listCollecton(dbGetCol)
await db.dropCollection(dbGetCol)
} catch(error){ console.log(error) }
}
和db.js
//db.js
require('dotenv').config()
const { MongoClient } = require('mongodb')
const promisify = require('es6-promisify')
let _connection
const connect = (url) => {
if (!process.env.MONGO_CONNECTION_STRING) {
throw new Error(`Environment variable MONGO_CONNECTION_STRING must be set to use API.`)
}
let prom = promisify(MongoClient.connect)(url)
console.log(prom)
return prom
};
/**
* Returns a promise of a `db` object. Subsequent calls to this function returns
* the **same** promise, so it can be called any number of times without setting
* up a new connection every time.
*/
const connection = (url) => {
if (!_connection) {
_connection = connect(url)
}
return _connection
}
exports.connection = connection
class Db {
constructor(dbName) {
this.dbName = dbName
}
async getCollection(collectionName) {
try{
const db = await connection(process.env.MONGO_CONNECTION_STRING+this.dbName )
let getCol = await db.collection(collectionName)
if (process.env.TEST=='TEST'){
console.log('Database Name: '+this.dbName)
console.log('1 TEST OK - '+collectionName+' - Database created!')
}
return getCol
} catch(error) { console.log("getCollection DB Error!") }
}
async insertInCollection(collection, data) {
try{
let insert = await collection.insertOne(data)
if (process.env.TEST=='TEST'){
console.log('2- insertInCollectionDB OK')
console.log(data)
}
return insert
} catch(error) { console.log(" insertInCollectionDB Error!") }
}
async getOneFromQuery (collection, query){
try{
let result = await collection.find(query).limit(1).toArray()
if (process.env.TEST=='TEST'){
console.log('3- query One OK')
console.log(result)
}
return result
} catch(error) { console.log("queryDB Error!")}
}
async getAllFromQuery(collection, query){
try{
let result = await collection.find(query).toArray()
if (process.env.TEST=='TEST'){
console.log('4- query All OK')
console.log(result)
}
return result
} catch(error) { console.log("queryDB Error!")}
}
async listCollecton(collection){
try{
let list = await collection.find().toArray()
if (process.env.TEST=='TEST'){
console.log('5- List All elems in Collection OK');
console.log(list)
}
return list
} catch(error) { console.log( "listCollecton Error!")}
}
async dropCollection(collection){
try{
let drop = await collection.drop()
if (process.env.TEST=='TEST'){
console.log('6 - dropCollectionDB OK')
}
return drop
} catch(error) { console.log("dropCollectionDB Error!")}
}
}
exports.Db = Db