Mongoose.js: remove collection or DB

前端 未结 6 1960
遥遥无期
遥遥无期 2020-11-30 08:23

Is it possible to remove collection or entire db using mongoose.js?

相关标签:
6条回答
  • 2020-11-30 08:47

    Mongoose references the connection on every model. So, you may find it useful to also drop the DB or collection off of an individual model.

    For example:

    // Drop the 'foo' collection from the current database
    User.db.dropCollection('foo', function(err, result) {...});
    
    // Drop the current database
    User.db.dropDatabase(function(err, result) {...});
    
    0 讨论(0)
  • 2020-11-30 08:49

    This can now be done in Mongoose.

    MyModel.collection.drop();
    

    Hat tip: https://github.com/Automattic/mongoose/issues/4511

    0 讨论(0)
  • 2020-11-30 08:51

    For those that are using the mochajs test framework and want to clean all db collections after each test, you can use the following which uses async/await:

    afterEach(async function () {
      const collections = await mongoose.connection.db.collections()
    
      for (let collection of collections) {
        await collection.remove()
      }
    })
    
    0 讨论(0)
  • 2020-11-30 08:52

    For 5.2.15 version of Mongoose + Mocha tests usage where you need to drop all collections before each test.

    beforeEach(async () => {
         const collections = await mongoose.connection.db.collections();
    
         for (let collection of collections) {
              // note: collection.remove() has been depreceated.        
              await collection.deleteOne(); 
         }
    });
    
    0 讨论(0)
  • 2020-11-30 09:05

    If want to drop collection after tests and your test were running in a docker container:

    mongoose = require("mongoose");
    ...
    afterAll(async () => {
      const url = 'mongodb://host.docker.internal:27017/my-base-name';
      await mongoose.connect(url)
      await mongoose.connection.collection('collection-name').drop()
    })
    
    0 讨论(0)
  • 2020-11-30 09:12

    Yes, although you do it via the native MongoDB driver and not Mongoose itself. Assuming a required, connected, mongoose variable, the native Db object is accessible via mongoose.connection.db, and that object provides dropCollection and dropDatabase methods.

    // Drop the 'foo' collection from the current database
    mongoose.connection.db.dropCollection('foo', function(err, result) {...});
    
    // Drop the current database
    mongoose.connection.db.dropDatabase(function(err, result) {...});
    
    0 讨论(0)
提交回复
热议问题