Nedb 非唯一_id 索引

Nedb non-unique _id indexing

我的 electron.js 应用程序有一个 Nedb 数据库,即使 ensureIndex({… unique: true}) 也能生成 _id 副本。单击时,索引值将增加 5 - 而不是使用该值生成新索引。示例:

// 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}

相关代码:

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>

已尝试修改变量类型、重新排序函数等 - 均无济于事。 GitHub documentation 声称 _id 默认是唯一索引的,但在我的使用中并非如此。

有什么解决方法吗?

假设您在查看正在写入数据库的物理文件时看到这些 "duplicates",则一切正常。

来自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.