nedb method update and delete creates a new entry

2019-06-25 10:11发布

I'm using nedb and I'm trying to update an existing record by matching it's ID, and changing a title property. What happens is that a new record gets created, and the old one is still there. I've tried several combinations, and tried googling for it, but the search results are scarce.

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

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

What's even crazier when performing a delete, a new record gets added again, but this time the record has a weird property: {"$$deleted":true,"_id":"WFZaMYRx51UzxBs7"}

This is the code that I'm using:

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

1条回答
叼着烟拽天下
2楼-- · 2019-06-25 10:40

In the nedb docs it says followings :

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.

I didn't use this but it seems , it uses localStorage and it has append-only format for update and delete methods.

When investigated its source codes, in that search in persistence.tests they wanted to sure checking $$delete key also they have mentioned `If a doc contains $$deleted: true, that means we need to remove it from the data``.

So, In my opinion you can try to compacting db manually, or in your question; second way can be useful.

查看更多
登录 后发表回答