89

Вопрос по node.js, mongodb, mongoose – Как удалить базу данных с помощью Mongoose?

Я готовлю сценарий создания базы данных в Node.js и Mongoose. Как я могу проверить, существует ли база данных, и если да, удалить (удалить) ее, используя Mongoose?

Я не мог найти способ бросить это с Мангустом.

Error: User Rate Limit Exceeded<a href="http://stackoverflow.com/questions/11453617/mongoose-js-remove-collection-or-db" title="mongoose js remove collection or db">stackoverflow.com/questions/11453617/&#x2026;</a>

Oct 13, 2016, 4:56 AMот

12ответов

4

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

Error: User Rate Limit Exceeded

  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.
73

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

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

Error: User Rate Limit Exceeded

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

Error: User Rate Limit Exceeded

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

Warning

Error: User Rate Limit Exceeded

8

Error: User Rate Limit Exceeded

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

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

4

Error: User Rate Limit ExceededError: User Rate Limit Exceeded):

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

Error: User Rate Limit ExceededuseMongoClientError: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

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!

3

Error: User Rate Limit Exceeded

mongoose.connection.dropDatabase();

Error: User Rate Limit Exceeded

mongoose.connection.db.dropDatabase();

Error: User Rate Limit Exceeded.find()Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededdropDatabase()Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededalwaysError: User Rate Limit ExceededdropDatabaseError: User Rate Limit ExceededopenError: User Rate Limit Exceeded

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;
};

Error: User Rate Limit Exceeded

// 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);
    }
}  
0

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

Error: User Rate Limit Exceededv4.7.0:

mongoose.connection.dropDatabase();
14

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

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

Error: User Rate Limit Exceeded

-1

Error: User Rate Limit Exceeded

myMongooseModel.collection.drop();

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

1

Error: User Rate Limit Exceeded

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

Error: User Rate Limit Exceeded

TypeError: Cannot read property 'commandsTakeWriteConcern' of null

5

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

This relies on the Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

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

RelatedQuestions