Adam Farver
Adam Farver

Reputation: 48

Getting current collections in MongoDB from MongooseJS 5.x

I'm working on a demo project that resets my mongodb collections every hour. I got how use cron in my node project. What I can't figure out is how to get the collection names. I've looked at other solutions but it seems that there was a way in earlier versions of mongoose but not V5.

console.log(mongoose.connection.db) // Undefined

So, basically, I want to be able to get an array of the current collections to programmatically drop them and reseed the DB.

async function reloadDb(){
// Get collection names
const collectionNames = await mongoose.connection.db    //undefined but I want array
// Map through results....
{...}

}

Upvotes: 0

Views: 49

Answers (2)

Boris Kukec
Boris Kukec

Reputation: 721

In similar situations, I always go low as possible, for example, using MongoDB client directly, and dropping collections approximately like this, (this answer is appropriate for dropping, is not quite clear if dropping or clear of collections was needed):

const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const connectionURL = 'mongodb://localhost'

const client = new MongoClient(connectionURL, { useNewUrlParser: true, useUnifiedTopology: true });

const drop = async (databaseName) => {
    await client.connect().then(() => {
        const db = client.db(databaseName);
        const collections = db.listCollections();
        collections.forEach(element => {
            db.dropCollection(element.name);
        });
    }).catch(error => {
        console.log("ERROR:", error) // or some logger
    })
}

exports.drop = drop;

Upvotes: 1

J.F.
J.F.

Reputation: 15187

You can get collections using Object.keys(mongoose.connection.collections);

Also, to reset DB programatically loop over every collection you can do:

const collections = mongoose.connection.collections;
for (const key in collections) {
    const collection = collections[key];
    await collection.deleteMany();
}

Upvotes: 0

Related Questions