简体   繁体   中英

Is there a way to delete all collections in a database except the one ? nodejs mongodb, mongoose

I am having multiple collections inside a single database. I have basically created collections name by current date like 20220829, 20220830, 20220831 (these are collection names). I want to keep only 20220831 collection (the latest one) and basically delete all others in that database. Is there a way to do this optimally?

Please refer following code snip

afterEach(async function () {

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

let todaysDate = yyyy+mm+dd

const collections = await mongoose.connection.db.collections()

  for (let collection of collections) {
    if(collection !== todaysDate)
    await collection.remove();
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM