mongooseを使って、dbを一括で消す方法


概要

❯ mongo
MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:27017
WARNING: No implicit session: Logical Sessions are only supported on server versions 3.6 and greater.
Implicit session: dummy session
MongoDB server version: 3.4.20
WARNING: shell and server versions do not match
Server has startup warnings:
2020-06-23T01:59:36.690+0000 I STORAGE  [initandlisten]
2020-06-23T01:59:36.690+0000 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2020-06-23T01:59:36.690+0000 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2020-06-23T01:59:39.381+0000 I CONTROL  [initandlisten]
2020-06-23T01:59:39.381+0000 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-06-23T01:59:39.381+0000 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-06-23T01:59:39.381+0000 I CONTROL  [initandlisten]
> show dbs
admin                                            0.000GB
my_db                                            0.881GB
my_db_test_4e95cefc_26c9_42ea_801e_872f86090ade  0.000GB
my_db_test_5e95cefc_26c9_42ea_801e_872f86090ade  0.000GB
my_db_test_6e95cefc_26c9_42ea_801e_872f86090ade  0.000GB
local                                            0.000GB

このように、 my_db_hogehoge のように、testを実行するたびにmongoにdbが作られてしまっていて困っていました。
このmy_db_hogehogeを一括で削除するコマンドを作りました

実装

環境

❯ node --version
v10.16.3
❯ npm --version
6.9.0
package.json
{
  "dependencies": {
    "mongodb": "2.2.10",
    "mongoose": "5.2.10",
  },
  "devDependencies": {
    "@types/mongodb": "2.2.x",
    "@types/mongoose": "5.2.x",
  },
}

コード

removeTestDB.js
'use strict';

const mongoose = require('mongoose');
const { execSync } = require('child_process');

const dbName = 'my_db_test';
mongoose.connect('mongodb://localhost:27017').then(async () => {
  mongoose.connection.db.admin().command({ listDatabases: 1 }, (err, result) => {
    if (err) {
      console.log(err);
      throw err;
    }
    const testDBs = result.databases.map(d => d.name).filter(d => d.includes(dbName));
    testDBs.forEach(d => {
      execSync(`mongo ${d} --eval "db.dropDatabase()"`);
      console.log(`${d} is deleted`);
    });
    console.log(`all ${dbName} is deleted`);
    mongoose.disconnect();
  });
}).catch(err => {
  console.log(err);
  throw err;
});
  1. mongoose.connection.db.admin().command({ listDatabases: 1 } (err, result) => {})
    • こちらで、dbのリストを取得。(show dbs と同じ効果)
  2. execSync(mongo ${d} --eval "db.dropDatabase()");
    • こちらで、my_db_testの名前を含むdbを削除

おわりに

限定的かつ実用性はあまりなさそうなコードですが、メモがてら。
execSyncで実行しているのが少し微妙な気がするので、mongooseの機能で出来るならやりたいですね。