Nedb non-unique _id indexing

1.1k Views Asked by At

I have a Nedb database for my electron.js app that generates _id replicas even with ensureIndex({… unique: true}). Onclick, an indexed value is to increment by 5 - instead a new index is generated with said value. Example:

// Before click
{"_id":0,"testVal":0}
{"_id":1,"testVal":0}
{"_id":2,"testVal":0}
…
// After click
{"_id":0,"testVal":0} // Intended: {"_id":0, "testVal":5}
{"_id":1,"testVal":0}
{"_id":2,"testVal":0}
…
{"_id":0,"testVal":5}

Relevant code:

var Datastore = require('nedb'); 
db = new Datastore ({filename: 'db/rtest.db', autoload: true}); 

// Database functions
exports.createTestVal = function(i, passVal) {
  var test = {_id: i, testVal: passVal};
  db.insert(test, function(err, newDoc){})};

exports.updateTestVal = function(i, passVal) {
db.update({_id: i}, {$set: {"testVal": passVal}}, {}, function(err, numReplaced){});}

exports.getTestVal = function(fnc){
  db.find({}, function(err, docs) {fnc(docs)})}

exports.deleteTestVal = function(id) {
  db.remove({_id: id}, {}, function(err, numRemoved){})}

// Event functions
const database = require('../assets/js/testdatabase'); // 'testdatabase' = code above

var btnTst = document.getElementById('add5'); var i = 0;
db.ensureIndex({ fieldName: "_id", unique: true }, function (err) {});

btnTst.addEventListener('click', function(event){
  var value = Number(this.value);
  database.updateTestVal(i, value);
  i++;})

window.addEventListener('load', function() {
    database.getTestVal(function(testVals) {
    for (k = 0; k < 10; k++) {if (testVals.length == k){fillValues(k)}}})})  

function fillValues(k){for (p = k; p < 10; p++){database.createTestVal(p, 0)}}
<button id="add5" value=5>+5</button>

Tried modifying variable types, reordering functions, among others - to no avail. The GitHub documentation claims that _id is uniquely-indexed by default, but isn't so in my use.

Any workarounds?

1

There are 1 best solutions below

0
On BEST ANSWER

Assuming that you are seeing these "duplicates" while viewing the physical file that your database is being written to, everything is working as expected.

From the NeDB documentation:

Persistence

Under the hood, NeDB's persistence uses an append-only format, meaning that all updates and deletes actually result in lines added at the end of the datafile, for performance reasons. The database is automatically compacted (i.e. put back in the one-line-per-document format) every time you load each database within your application.