1
我正在研究Koa + Mongodb後端。我的問題是:什麼時候應該關閉數據庫,或者Mongodb是否管理該數據庫,因爲我現在沒有關閉它們,看起來沒問題。Mongodb + Node:何時關閉
// app.js
const Koa = require('koa')
const database = require('./database')
const app = new Koa()
database
.connet()
.then(() => {app.listen(':8080')})
.catch((err) => {console.error(err)})
// ./database.js
const MongoClient = require('mongodb').MongoClient
const Model = require('./model')
class Database {
async connect() {
if (!db) {
db = await MongoClient.connect("localhost:27017")
this.item = new Model(db, 'item_collection')
}
}
}
module.exports = new Database()
// ./model.js
class Model {
constructor(db, collectionName) {
this.name = collectionName
this.database = database
}
async findAll() {
const result = await this.db.collection(this.name).find().toArray()
if (!result) {
throw new Error('error')
}
return result
}
}
module.exports = Model
我也跑使用貝吉塔作出API請求到服務器100的請求/秒的應力測試和響應時間是好的。那麼,我擔心這裏的過早優化嗎?如果沒有,我應該什麼時候關閉數據庫?