441020
有几个关于 mongodb 原生驱动的问题?
第一个,简单封装问题
// 连接数据库并选定集合然后返回
const { MongoClient } = require('mongodb');
const { db } = require('config-lite')(__dirname);
const { format } = require('url')
const _ = require('lodash')
const url = format(_.omit(db.mongodb, 'collection'));
/*
db.mongodb 类似
{
protocol: 'mongodb:',
hostname: '127.0.0.1',
slashes: true,
auth: null,
port: '27017',
pathname: '/xxxx',
collection: {
post: 'posts',
admin: 'admins',
}
*/
module.exports = function(collection, fieldOrSpec, options) {
return MongoClient.connect(url)
.then(db => {
return db.collection(collection)
})
.then(col => {
return !_.isUndefined(fieldOrSpec) && _.isPlainObject(fieldOrSpec)
? col.createIndex(fieldOrSpec, options)
.then((indexName) => {
return col
})
: col
})
};
// 增删查改操作,截取部分
const connect = require('./_connect_v2');
const isPlainObject = require('lodash/isPlainObject')
module.exports = {
count(collection, query, options) {
return isPlainObject(collection)
? connect(...Object.values(collection))
.then(col => {
return col.count(query, options)
})
: connect(collection)
.then(col => {
return col.count(query, options)
})
},
distinct(collection, key, query, options) {
return isPlainObject(collection)
? connect(...Object.values(collection))
.then(col => {
return col.distinct(key, query, options)
})
: connect(collection)
.then(col => {
return col.distinct(key, query, options)
})
},
insertOne(collection, data, options) {
return isPlainObject(collection)
? connect(...Object.values(collection))
.then(col => {
return col.insertOne(data, options)
})
: connect(collection)
.then(col => {
return col.insertOne(data, options)
})
}
}
不封装可能会有很长的链式操作,但是这样封装又会造成 没办法 db.close,并且我也有几个疑惑:
第一个问题: MongoClient.connect 是每次都会创建一个拥有一定数量的连接池么?如果是这样那我只是单次数据库查询不是会很不高效,比如我只需要获得一个集合的文档总数
第二个问题: 查询资料的过程中有说 MongodbClient.connect 是维护了一个 100 个连接的连接池,也有人放官网图说是 改成了单例模式,我想问的就是到底是哪种(虽然第二种可能性很小)? 并且mongodb单例模式在 Nodejs 中的实现是否会有所不同,因为 Nodejs 表面单线程,底层还是多线程实现异步,总之我对这些知识很混乱,希望有人能讲一下。