Advertisement
CastleMan2000

dbdelete.js

Nov 29th, 2018
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var unifiedIO = require('../unifiedIO.js');
  2. // This is a module I wrote to make the bot able to output either Discord messages or console.log() messages.
  3.  
  4.  
  5. module.exports = {
  6.     name: 'dbdelete',
  7.     aliases: ['dbremove' , 'dbd'],
  8.     cooldown: 1,
  9.     description: 'Removes stuff from the database (Internal)',
  10.     usage: '__collection__ __item__',
  11.     execute: async function(msg, args, db) {
  12.        
  13.         if (!args.length) {
  14.             unifiedIO.print('Give me a collection, and an item to delete from it...',msg);
  15.         } else if (args.length == 1) {
  16.             unifiedIO.print('Use `!help ' + this.name + '` to see usage.',msg);
  17.         }
  18.         else
  19.         {
  20.             if (!db) {
  21.                 unifiedIO.print('Database is not mounted.',msg);
  22.             }
  23.             if (db) {
  24.                
  25.                 try {
  26.                    
  27.                     var selectedCollection = args[0];
  28.                     var selectedItem = "";
  29.                    
  30.                     if (args.length > 2) {
  31.                         for(i = 1; i < args.length - 1; i++)
  32.                         {
  33.                             selectedItem += args[i] + ' ';
  34.                         }
  35.                        
  36.                         selectedItem += args[args.length - 1];
  37.                     } else {
  38.                         selectedItem = args[1];
  39.                     }
  40.                    
  41.                     //console.log("Selected collection: " + selectedCollection);
  42.                     //console.log("Item selected to be removed: " + selectedItem);
  43.                    
  44.                    
  45.                    
  46.                     // Get the list of collection names
  47.                     let collecsListArray = await db.listCollections({},{nameOnly: true}).toArray();
  48.                     var collecNames = new Array ();
  49.                    
  50.                     for (i = 0; i < collecsListArray.length; i++) {
  51.                         collecNames[i] = collecsListArray[i].name;
  52.                     }
  53.                    
  54.                    
  55.                    
  56.                     // First, we need to check if the collection is actually in the DB.
  57.                     unifiedIO.debugLog("Did the user give a collection that exists? : " + collecNames.includes(selectedCollection));
  58.                    
  59.                     if (!collecNames.includes(selectedCollection)) {
  60.                         unifiedIO.print("Error: " + selectedCollection + " is not a valid collection.",msg);
  61.                         return;
  62.                     }
  63.                    
  64.                    
  65.                     // Next, we need to check if the item is actually in the collection.
  66.                    
  67.                     var query = { value: { $eq: selectedItem} };
  68.                     let numOfFind = await db.collection(selectedCollection)
  69.                                             .find(query)
  70.                                             .count();
  71.                    
  72.                     //console.log("Number of matches: " + numOfFind);
  73.                     if (numOfFind == 0) {
  74.                         unifiedIO.print("Error: No matches in given collection.",msg);
  75.                         return;
  76.                     }
  77.                    
  78.                    
  79.                     // DELETE selectedCollection WHERE value = selectedItem
  80.                     db.collection(selectedCollection).deleteMany(query, function(err, result) {
  81.                         if (err) {
  82.                             throw err;
  83.                            
  84.                             console.log('Something went wrong...?');
  85.                             return; //dont sort or change the count if we couldnt remove an element
  86.                         }
  87.                         unifiedIO.debugLog("Documents removed: " + result.deletedCount);
  88.                         unifiedIO.debugLog('"' + selectedItem + '" has been removed from ' + selectedCollection + '.');
  89.                         correctIDs(db,selectedCollection);
  90.                     });
  91.                    
  92.                    
  93.                    
  94.                    
  95.                 }
  96.                 catch(err)
  97.                 {
  98.                     console.log(err);
  99.                     unifiedIO.print('Something went wrong...',msg);
  100.                 }
  101.                
  102.             }
  103.         }
  104.        
  105.     },
  106. };
  107.  
  108. var correctIDs = async function(db,selectedCollection) {
  109.     /* This function takes a "messed up" sequence of IDs
  110.         (For example:
  111.         { "_id" : 2, "value" : "tightly" }
  112.         { "_id" : 4, "value" : "merrily" }
  113.         { "_id" : 9, "value" : "tiredly" }
  114.         { "_id" : 1, "value" : "firmly" }
  115.         )
  116.         and corrects it so that they are in order, with no gaps
  117.         { "_id" : 1, "value" : "firmly" }
  118.         { "_id" : 2, "value" : "tightly" }
  119.         { "_id" : 3, "value" : "merrily" }
  120.         { "_id" : 4, "value" : "tiredly" }
  121.         AND it updates the seq in counters.
  122.     */
  123.  
  124.     // First, we grab the whole collection, sorted in order by _id.
  125.     var sortedCollec = await db.collection(selectedCollection).find().sort({_id: 1}).toArray();
  126.     //unifiedIO.debugLog(sortedCollec);
  127.    
  128.     //  TODO: Use this sorted collection to check for negative IDs
  129.     //        If the first item's ID is negative, then we can commence checking, one by one
  130.     //        until we hit a positive ID.
  131.     //  old comment: //fixNegativeIDs(); // Use a db.find operation to check for negative IDs? or... use the sorted thing?
  132.  
  133.     // Normalize document sequence numbers.
  134.     // Remember that this only occurs if the user has succesfully deleted something.
  135.     // NOTE THAT THIS CODE DOES NOT WORK
  136.     // IF ANY _IDS HAVE NEGATIVE SEQ VALUES!!
  137.     // IT WILL HAVE A DUPLICATE KEY ERROR!!
  138.     for (let i = 0; i <= sortedCollec.length - 1; i++) {
  139.         let ithID = sortedCollec[i]._id;
  140.    
  141.         // Is the ith document's ID equal to i + 1? (+1 so the IDs start at 1, not 0)
  142.         if (ithID != i + 1) {
  143.             // If not, then make it so.
  144.             sortedCollec[i]._id = i + 1;
  145.        
  146.                 // Remove the offending doc...
  147.             db.collection(selectedCollection).deleteOne({_id: ithID})
  148.             .then((result) => {
  149.                 //console.log("Deleted {" + ithID + "," + sortedCollec[i].value + "}.");
  150.             })
  151.             .then(() => {
  152.                 // ...then re-insert the doc with the proper ID.
  153.                
  154.                 //console.log("Attempting to insert {" + (i + 1) + "," + sortedCollec[i].value + "}.");
  155.                 db.collection(selectedCollection).insertOne({_id: i + 1, value: sortedCollec[i].value});
  156.             })
  157.             .catch((err) => { throw err; });
  158.        
  159.         }
  160.    
  161.     }
  162.  
  163.     // Update the corresponding seq.
  164.     db.collection("counters").findOneAndUpdate({_id: selectedCollection}, {$set: {"seq": sortedCollec.length}})
  165.     .then(() => {
  166.         unifiedIO.debugLog("Updated counters. Current seq: " + sortedCollec.length);
  167.     })
  168.     .catch((err) => { throw err; });;
  169. }
  170.  
  171. // TODO: Add a bit which fixes negative IDs
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement