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

89

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

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

Error: User Rate Limit Exceededstackoverflow.com/questions/11453617/… Uday Hiwarale

Ваш Ответ

12   ответов
73

var mongoose = require('mongoose');
/* Connect to the DB */
mongoose.connect('mongodb://localhost/mydatabase',function(){
    /* Drop the DB */
    mongoose.connection.db.dropDatabase();
});
Error: User Rate Limit Exceeded
dropDatabase, кажется, не работает в некоторых случаях, но прямая команда Монго все еще может быть использованаmongoose.connection.db.executeDbCommand( {dropDatabase:1}, function(err, result) { if (err) { console.log(err); } done(); });
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededmongoose.connection.db.dropDatabase()Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededdropDatabaseError: User Rate Limit ExceededconnectError: User Rate Limit Exceededmongoose.connect('...', function() { ...dropDatabase()}).
4

To empty a particular collection in a database:

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

Error: User Rate Limit Exceeded

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

Error: User Rate Limit Exceededv4.7.0:

mongoose.connection.dropDatabase();
-1

Error: User Rate Limit Exceeded

myMongooseModel.collection.drop();

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

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

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

1

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

TypeError: Cannot read property 'commandsTakeWriteConcern' of null

connectError: User Rate Limit Exceeded.then((connection) => { ... });Error: User Rate Limit Exceededmongoose.connectError: User Rate Limit Exceededmongoosejs.com/docs/connections.html
14

//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 Exceededdb = mongoose.createConnection(cfg.mongo.uri, cfg.mongo.db);
Error: User Rate Limit ExceededconnectError: User Rate Limit ExceededdropDatabaseError: User Rate Limit ExceededconnectError: User Rate Limit ExceededopenError: User Rate Limit Exceeded
Error: User Rate Limit Exceededmongoose.connectError: User Rate Limit ExceededmongooseError: User Rate Limit Exceededconn = mongoose.connect(...)Error: User Rate Limit Exceededmongoose.connect(...)Error: User Rate Limit Exceededconn = mongooose.connection.
4

):

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

useMongoClient

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

This relies on the

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

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

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

Error: User Rate Limit Exceeded Yaron Naveh
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded

Похожие вопросы