Thursday 20 April 2017

Mongodb + Node: When to close

I am working on a Koa + Mongodb backend. My question is: When should I close the db, or does Mongodb manage that because I am not closing any of them right now and it seems fine.

// 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

I also ran a stress test using vegeta to make API request to the server at 100 request / second and the response time is good. So, am I worried about premature optimization here? If not, when should I close the db?



via JSNoob

No comments:

Post a Comment