javascriptnode.jsnode-moduleslokijs

How to delete a Collection in LokiJS


I been working on LokiJS on Node recently, And I could'nt find a command that deletes the entire Collection itself,

I tried with these commands with an assumption it would exist, I could not find any docs/ samples to delete a collection.

// let result = this.db.dropCollection(collectionName); // let result = this.db.removeCollection(collectionName); // let result = this.db.deleteCollection(collectionName);

Other way around I know I can achieve the same by reading the file and removing the entire object, But is there a built-in LokiJS function?


Solution

  • To delete a collection you need to use the removeCollection() method on the main Loki object. See docs here.

    For example, if you have your Loki instance initialized like this:

    const loki = require('lokijs');
    const lokidb = new loki();
    
    // Add a collection (that we will remove later)
    let myCollection = lokidb.addCollection('myCollection');
    

    Now lokidb is your main loki object, and this is the object that you need to execute the removeCollection() from.

    // Let's remove the collection
    lokidb.removeCollection('myCollection');
    
    // * poof * ....
    // myCollection is now gone
    
    // To make sure that this deleting change is persisted (if necessary)
    lokidb.saveDatabase();
    

    I don't know exactly how you have your loki db set up, but hopefully this example helps.