2017-04-20 4 views
1

私はKoa + Mongodbバックエンドで作業しています。私の質問は次のとおりです。いつDBを閉じるか、または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

また、私は100のリクエスト/秒のサーバにAPIリクエストを作成するベジータを使用してストレステストを実行し、応答時間が良いです。だから、ここで早すぎる最適化が心配ですか?そうでない場合、いつDBを閉じるべきですか?興亜が稼働し続けたよう

答えて

1

あなたはがないは、DB接続を閉じる必要があります(そして、あなたのケースでポート8080でリスニング)。

終了する予定のスクリプト(cronなどで実行中のタスク)を実行している場合は、すべてのdbタスクが終了したら手動で接続を閉じる必要があります。

express.js(Koaの姉妹フレームワーク)のthis exampleをご覧ください。

関連する問題