Add check before dropping collection

This commit is contained in:
Fred Boniface 2023-01-11 10:21:27 +00:00
parent 1c269571b7
commit 0317dc723a
1 changed files with 16 additions and 12 deletions

View File

@ -13,20 +13,24 @@ const client = new MongoClient(uri);
const db = client.db(dbName);
async function dropCollection(coll){
log.out(`DbAccess.dropCollection: checking if collection exists: ${coll}`)
//Some Code Here:
await client.connect();
var cols = await db.listCollections().toArray()
log.out(`dbAccess.dropCollection: Existing collections: ${JSON.stringify(cols)}`)
// If (any object in the Array contains name:{coll} then exsists. If not doesn't exist.)
// If Collection Exists:
log.out(`DbAccess.dropCollection: dropping collection: ${coll}`)
// check if collection contains any documents, if it doesn't, it is either empty or non-existent - it doesn't need dropping.
var collection = db.collection(coll);
var count = await collection.countDocuments();
log.out(`DbAccess.dropCollection: Collection '${coll}' contains ${count} documents`)
if (count == 0) {
log.out(`DbAccess.dropCollection: Collection '${coll}' is empty. Do not need to drop`)
} else {
log.out(`DbAccess.dropCollection: dropping collection: '${coll}'`)
db.dropCollection(coll);
log.out(`DbAccess.dropCollection: dropped collection: ${coll}`)
// Else Do Nothing
log.out(`DbAccess.dropCollection: dropped collection: '${coll}'`)
}
// ALTERNATIVE METHOD - Appears to not be needed:
// This code returns and prints an array containing an object for each existing collection.
// var cols = await db.listCollections().toArray()
// log.out(`dbAccess.dropCollection: Existing collections: ${JSON.stringify(cols)}`)
// If (any object in the Array contains name:{coll} then exsists. If not doesn't exist.)
}
async function putCorpus(data){