IT박스

Mongoose로 데이터베이스를 삭제하는 방법은 무엇입니까?

itboxs 2020. 8. 26. 07:42
반응형

Mongoose로 데이터베이스를 삭제하는 방법은 무엇입니까?


Node.js와 Mongoose에서 데이터베이스 생성 스크립트를 준비 중입니다. 데이터베이스가 이미 존재하는지 확인하려면 어떻게해야하나요? 그렇다면 Mongoose를 사용하여 삭제 (삭제)하세요?

몽구스와 함께 떨어 뜨리는 방법을 찾지 못했습니다.


mongoose에서 컬렉션을 삭제하는 방법은 없습니다. 최선의 방법은 하나의 콘텐츠를 삭제하는 것입니다.

Model.remove({}, function(err) { 
   console.log('collection removed') 
});

하지만이를 위해 사용할 수있는 mongodb 네이티브 자바 스크립트 드라이버에 액세스하는 방법이 있습니다.

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

경고

문제가 발생할 경우를 대비하여이를 시도하기 전에 백업을 만드십시오!


Mongoose는 연결에 데이터베이스가없는 경우 데이터베이스를 생성하므로 일단 연결하면 데이터베이스에 어떤 것이 있는지 쿼리 할 수 ​​있습니다.

연결된 모든 데이터베이스를 삭제할 수 있습니다.

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

@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();

HTH는 적어도 나를 위해 했으므로 공유하기로 결정했습니다 =)


@hellslam 및 @silverfighter의 답변을 시도했습니다. 내 테스트를 방해하는 경쟁 조건을 발견했습니다. 제 경우에는 모카 테스트를 실행 중이고 테스트의 이전 기능에서는 전체 DB를 지우고 싶습니다. 여기에 저에게 적합한 것이 있습니다.

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

자세한 내용은 https://github.com/Automattic/mongoose/issues/1469를 읽을 수 있습니다.


다른 솔루션에서 내가 가진 어려움은 인덱스를 다시 작동 시키려면 애플리케이션을 다시 시작해야한다는 것입니다.

내 필요에 따라 (즉, 단위 테스트를 실행하여 모든 컬렉션을 핵무기 한 다음 인덱스와 함께 다시 생성 할 수 있음)이 솔루션을 구현했습니다.

This relies on the underscore.js and async.js libraries to assemble the indexes in parellel, it could be unwound if you're against that library but I leave that as an exerciser for the developer.

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

An updated answer, for 4.6.0+, if you have a preference for promises (see docs):

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

I tested this code in my own code, using mongoose 4.13.6. Also, note the use of the useMongoClient option (see docs). Docs indicate:

Mongoose's default connection logic is deprecated as of 4.11.0. Please opt in to the new connection logic using the useMongoClient option, but make sure you test your connections first if you're upgrading an existing codebase!


To empty a particular collection in a database:

model.remove(function(err, p){
    if(err){ 
        throw err;
    } else{
        console.log('No Of Documents deleted:' + p);
    }
});

Note:

  1. Choose a model referring to particular schema(schema of collection you wish to delete).
  2. This operation will not delete collection name from database.
  3. This deletes all the documents in a collection.

This works for me as of Mongoose v4.7.0:

mongoose.connection.dropDatabase();

The best way to drop your database in Mongoose depends on which version of Mongoose you are using. If you are using a version of Mongoose that 4.6.4 or newer, then this method added in that release is likely going to work fine for you:

mongoose.connection.dropDatabase();

In older releases this method did not exist. Instead, you were to use a direct MongoDB call:

mongoose.connection.db.dropDatabase();

However, if this was run just after the database connection was created, it could possibly fail silently. This is related to the connection actually be asynchronous and not being set up yet when the command happens. This is not normally a problem for other Mongoose calls like .find(), which queue until the connection is open and then run.

If you look at the source code for the dropDatabase() shortcut that was added, you can see it was designed to solve this exact problem. It checks to see if the connection is open and ready. If so, it fires the command immediately. If not, it registers the command to run when the database connection has opened.

Some of the suggestions above recommend always putting your dropDatabase command in the open handler. But that only works in the case when the connection is not open yet.

Connection.prototype.dropDatabase = function(callback) {
  var Promise = PromiseProvider.get();
  var _this = this;
  var promise = new Promise.ES6(function(resolve, reject) {
    if (_this.readyState !== STATES.connected) {
      _this.on('open', function() {
        _this.db.dropDatabase(function(error) {
          if (error) {
            reject(error);
          } else {
            resolve();
          }
        });
      });
    } else {
      _this.db.dropDatabase(function(error) {
        if (error) {
          reject(error);
        } else {
          resolve();
        }
      });
    }
  });
  if (callback) {
    promise.then(function() { callback(); }, callback);
  }
  return promise;
};

Here's a simple version of the above logic that can be used with earlier Mongoose versions:

// This shim is backported from Mongoose 4.6.4 to reliably drop a database
// http://stackoverflow.com/a/42860208/254318
// The first arg should be "mongoose.connection"
function dropDatabase (connection, callback) {
    // readyState 1 === 'connected'
    if (connection.readyState !== 1) {
      connection.on('open', function() {
        connection.db.dropDatabase(callback);
      });
    } else {
      connection.db.dropDatabase(callback);
    }
}  

Mongoose 4.6.0+:

mongoose.connect('mongodb://localhost/mydb')
mongoose.connection.once('connected', () => {
    mongoose.connection.db.dropDatabase();
});

Passing a callback to connect won't work anymore:

TypeError: Cannot read property 'commandsTakeWriteConcern' of null


beforeEach((done) => {
      mongoose.connection.dropCollection('products',(error ,result) => {
      if (error) {
        console.log('Products Collection is not dropped')
      } else {
        console.log(result)
      }
    done()
    })
  })

For dropping all documents in a collection:

myMongooseModel.collection.drop();

as seen in the tests

참고URL : https://stackoverflow.com/questions/10081452/how-to-drop-a-database-with-mongoose

반응형