如何使用Mongoose删除数据库?

Yar*_*veh 95 mongoose mongodb node.js

我正在Node.js和Mongoose中准备一个数据库创建脚本.如何检查数据库是否已存在,如果是,请使用Mongoose删除(删除)它?

我找不到用Mongoose放弃它的方法.

dri*_*hev 164

没有从mongoose中删除集合的方法,你可以做的最好是删除一个集合的内容:

Model.remove({}, function(err) { 
   console.log('collection removed') 
});
Run Code Online (Sandbox Code Playgroud)

但有一种方法可以访问mongodb本机javascript驱动程序,可用于此

mongoose.connection.collections['collectionName'].drop( function(err) {
    console.log('collection dropped');
});
Run Code Online (Sandbox Code Playgroud)

警告

在尝试此操作之前进行备份,以防出现任何问题!

  • 你有一个拼写错误 - 函数(错误)之后的额外逗号...应该是:mongoose.connection.collections ['collectionName'].drop(function(err){console.log('collection dropped') ;}); (3认同)
  • 我是唯一一个意识到这个答案没有解决如何删除数据库的问题的人.它没有要求删除它要求删除数据库的集合.. (3认同)
  • "没有办法从mongoose中删除一个集合",首先OP想要删除一个数据库,而不是一个colledtion,第二个@hellslam的答案下面的效果很好. (3认同)
  • 当我尝试第二个选项时,我得到"无法读取未定义的属性'collectionName'" (2认同)

小智 75

Mongoose将创建一个数据库(如果连接上尚不存在),因此一旦建立连接,您只需查询它以查看其中是否有任何内容.

您可以删除所有连接的数据库:

var mongoose = require('mongoose');
/* Connect to the DB */
mongoose.connect('mongodb://localhost/mydatabase',function(){
    /* Drop the DB */
    mongoose.connection.db.dropDatabase();
});
Run Code Online (Sandbox Code Playgroud)

  • 我发现`dropDatabase`调用应该放在`connect`的回调中,如`mongoose.connect('...',function(){... dropDatabase()})`. (12认同)
  • 我尝试了 `mongoose.connection.db.dropDatabase()` 但我发现数据库仍然存在?我错过了什么吗? (2认同)

sil*_*ter 14

如果您像这样修改@hellslam的解决方案,那么它将起作用

我使用这种技术在集成测试后删除数据库

//CoffeeScript
mongoose = require "mongoose"
conn = mongoose.connect("mongodb://localhost/mydb")

conn.connection.db.dropDatabase()

//JavaScript
var conn, mongoose;
mongoose = require("mongoose");
conn = mongoose.connect("mongodb://localhost/mydb");

conn.connection.db.dropDatabase();
Run Code Online (Sandbox Code Playgroud)

HTH至少它对我有用,所以我决定分享=)

  • 这很有帮助,谢谢!但是,你的变量名有点误导......`mongoose.connect`实际上返回`mongoose`.而不是`conn = mongoose.connect(...)`我会写`mongoose.connect(...)`然后`conn = mongooose.connection`. (2认同)

zaf*_*ani 8

试过@hellslam和@ silverfighter的答案.我发现一个竞争条件让我的测试恢复了.在我的情况下,我正在运行mocha测试,在测试的before函数中,我想擦除整个DB.这对我有用.

var con = mongoose.connect('mongodb://localhost/mydatabase');
mongoose.connection.on('open', function(){
    con.connection.db.dropDatabase(function(err, result){
        done();
    });
});
Run Code Online (Sandbox Code Playgroud)

您可以阅读更多https://github.com/Automattic/mongoose/issues/1469


小智 6

2020年更新

创建一个新文件,将其命名为 drop.js 并放入其中

require('dotenv').config()
const url = process.env.ATLAS_URI;
mongoose.connect(url, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
  useFindAndModify: false
});

const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})


mongoose.connection.dropDatabase().then(
  async() => {
   
    try {
      mongoose.connection.close()
     
    }
    catch (err) {
      console.log(err)
    }

 }
  
);
Run Code Online (Sandbox Code Playgroud)

在你的 package.json 中

in your package.json 
 "scripts": {
    
    "drop": "node models/drop.js",
   
  }
Run Code Online (Sandbox Code Playgroud)

在你的控制台上运行它并


Eri*_*ron 5

我对其他解决方案的困难在于,如果您想让索引再次运行,他们依赖于重新启动您的应用程序.

根据我的需求(即能够运行单元测试核武器所有集合,然后重新创建它们及其索引),我最终实现了这个解决方案:

这依赖于underscore.jsasync.js库来组装parellel中的索引,如果你反对那个库,它可以解开,但我把它作为开发人员的练习器.

mongoose.connection.db.executeDbCommand( {dropDatabase:1}, function(err, result) {
  var mongoPath = mongoose.connections[0].host + ':' + mongoose.connections[0].port + '/' + mongoose.connections[0].name
  //Kill the current connection, then re-establish it
  mongoose.connection.close()
  mongoose.connect('mongodb://' + mongoPath, function(err){
    var asyncFunctions = []

    //Loop through all the known schemas, and execute an ensureIndex to make sure we're clean
    _.each(mongoose.connections[0].base.modelSchemas, function(schema, key) {
      asyncFunctions.push(function(cb){
        mongoose.model(key, schema).ensureIndexes(function(){
          return cb()
        })
      })
    })

    async.parallel(asyncFunctions, function(err) {
      console.log('Done dumping all collections and recreating indexes')
    })
  })
})
Run Code Online (Sandbox Code Playgroud)


use*_*977 5

从 Mongoose 开始,这对我有用v4.7.0

mongoose.connection.dropDatabase();
Run Code Online (Sandbox Code Playgroud)


And*_*e M 5

如果您对诺言有偏爱,请为4.6.0+更新答案(请参阅docs):

mongoose.connect('mongodb://localhost/mydb', { useMongoClient: true })
.then((connection) => {
   connection.db.dropDatabase();
   // alternatively:
   // mongoose.connection.db.dropDatabase();
});
Run Code Online (Sandbox Code Playgroud)

我使用猫鼬4.13.6在自己的代码中测试了此代码。另外,请注意该useMongoClient选项的使用(请参阅docs)。文件显示:

从4.11.0开始,Mongoose的默认连接逻辑已弃用。请使用useMongoClient选项选择加入新的连接逻辑,但是如果要升级现有代码库,请确保先测试连接!