1

I'm using LokiJS and it's fine for most parts. Except that I can't seem to delete a record from the database.

The find gets me the right record to delete, but neither remove() not findAndRemove() remove it after saveDatabase. What am I doing wrong?

(Note: I've tried saveDatabase outside the loadDatabase(...) callback - no change. whenever I re-run it, the record I thought I deleted is still there)

Here's the code: dbName is a valid path to the file

var db = new loki(dbName);

db.loadDatabase({}, function (e) {

    var orders = db.getCollection("orders");

        console.log(orders.count() + " orders found... iterating");
        orders.find().forEach((v, i) => {
            console.log(i + "." + v.key + " " + v.places.display + " " + v.theme + " " + moment(v.date).format("DD MMM YYYY HH:mm"));
        });
    }

     let dKey = "some key that is valid";
        if (!dKey) {
            console.log("no key specified, returning");
            return;
        }
        console.log("deleting specific record " + dKey);
        let dObj = orders.find({ key: dKey });
        if (!dObj || dObj.length == 0) {
            console.log("no such record, returning");
            return;
        }
        console.log(dObj[0]);
        orders.remove(dObj[0]);
        db.saveDatabase((e) => {
            console.log("save complete");
        });
    }
});
Gerry
  • 866
  • 2
  • 12
  • 31

2 Answers2

3

Try: orders.chain().find({ key: dKey }).remove()

Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
1

I faced the same issue while working with lokijs, so putting it here so that it can help anyone else looking for the same issue in future.

I was trying to lookup a record in db with a particular $loki value, but I was getting an empty ResultSet. Then I tried this. data.chain().find({"$loki":{$aeq:serial}}).remove().data(). Here, data is my db instance and serial is the $loki value I was looking for and passing to find(). It seems like lokijs stores them as strings thats why $aeq worked and I was able to find and delete the required record

Mayank
  • 11
  • 1