nedb 方法更新和删除创建一个新条目而不是更新现有条目

nedb method update and delete creates a new entry instead updating existing one

我正在使用 nedb ,我正在尝试通过匹配 ID 并更改 title 属性 来更新现有记录。 发生的情况是创建了一条新记录,而旧记录仍然存在。 我尝试了几种组合,并尝试谷歌搜索,但搜索结果很少。

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

db.files.update(
  {_id: id}, 
  {$set: {title: title}}, 
  {}, 
  callback
);

更疯狂的是执行删除时,又添加了一条新记录,但是这次记录有一个奇怪的属性: {"$$deleted":true,"_id":"WFZaMYRx51UzxBs7"}

这是我正在使用的代码:

db.files.remove({_id: id}, callback);

在 nedb 文档中,它说了以下内容:

localStorage has size constraints, so it's probably a good idea to set recurring compaction every 2-5 minutes to save on space if your client app needs a lot of updates and deletes. See database compaction for more details on the append-only format used by NeDB.

Compacting the database

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. The reason for this is that disk space is very cheap and appends are much faster than rewrites since they don't do a seek. The database is automatically compacted (i.e. put back in the one-line-per-document format) everytime your application restarts.

You can manually call the compaction function with yourDatabase.persistence.compactDatafile which takes no argument. It queues a compaction of the datafile in the executor, to be executed sequentially after all pending operations.

You can also set automatic compaction at regular intervals with yourDatabase.persistence.setAutocompactionInterval(interval), interval in milliseconds (a minimum of 5s is enforced), and stop automatic compaction with yourDatabase.persistence.stopAutocompaction().

Keep in mind that compaction takes a bit of time (not too much: 130ms for 50k records on my slow machine) and no other operation can happen when it does, so most projects actually don't need to use it.

我没有使用它,但它似乎使用了 localStorage,并且它具有用于更新和删除方法的仅附加格式。

在调查其源代码时,in that search 在 persistence.tests 他们想确保检查 $$delete 密钥,他们还提到`如果文档包含 $$deleted: true,这意味着我们需要将其从数据中移除``。

因此,我认为您可以尝试手动或在您的问题中压缩数据库;第二种方法可能有用。