使用Mongoose,一次性删除数据库的方法

概述

❯ 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

我每次运行test时,都会在mongo中创建一个db,这让我感到困扰。因此,我创建了一个命令来批量删除名为my_db_hogehoge的db。

实施

环境

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

代码 (Mandarin Chinese)

'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) => {})

用这个方法,获取数据库的列表。(与show dbs相同的效果)

execSync(mongo ${d} –eval “db.dropDatabase()”);

用这个方法,删除包含my_db_test名称的db

结尾处

虽然这段代码似乎有限且不太实用,但只是为了做笔记而已。
因为在使用execSync执行的过程中稍显棘手,所以如果能够使用mongoose的功能来完成的话,我更愿意这样做。

广告
将在 10 秒后关闭
bannerAds