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?
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: