gpt4 book ai didi

database - Nedb 非唯一_id 索引

转载 作者:搜寻专家 更新时间:2023-10-30 22:25:34 25 4
gpt4 key购买 nike

我的 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 默认情况下是唯一索引的,但在我的使用中并非如此。

有什么解决方法吗?

最佳答案

假设您在查看正在写入数据库的物理文件时看到这些“重复项”,那么一切都按预期工作。

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

关于database - Nedb 非唯一_id 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52400306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com