5

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?

Teemu
  • 22,918
  • 7
  • 53
  • 106
Mahesh Kumaran
  • 887
  • 2
  • 12
  • 30

1 Answers1

3

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.

Adam D
  • 1,962
  • 2
  • 21
  • 37
  • 1
    I tried the same , but din't work, am i missing anything else ? – Mahesh Kumaran Jan 09 '19 at 12:01
  • Can you share a full example of your code, on a code pen, or a gist? – Adam D Jan 10 '19 at 10:23
  • 1
    Hey , i just found what the issue was , `lokidb.saveDatabase();` actually reflects the changes, infact i kept the autosave interval very less , still dint work - `lokidb.saveDatabase();`did the trick !! Thanks for the help !! – Mahesh Kumaran Jan 21 '19 at 09:39
  • @MaheshKumaran Glad you figured that out. I added your step in case any others have issues with persistence and autoSave like you did. If you want, check the answer as solved to help others. :-) – Adam D Jan 21 '19 at 12:35
  • 1
    Even with `db.card.findAndRemove({guid}); await new Promise((resolve, reject) => { db.loki.saveDatabase((err) => err ? reject(err) : resolve()); }); console.log(db.card.find({guid}));` still doesn't work. – Polv Mar 28 '19 at 18:50