Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NeDB not loading or storing to file

I cannot get the simplest example of NeDB to run properly. My code only works in-memory, persistence to file keeps failing without any error messages.

The error callbacks for the loaddatabase and insert events always pass a null reference as error, so no information there. Oddly it seems no one else has this issue, so I guess I'm missing something here. All help is much appreciated.

Here is the code:

var Datastore = require('nedb'), db = new Datastore({ filename: 'test.db' });

db.loadDatabase(function (err) {   
  alert(err); // err is null, with the autoload flag no error is thrown either
});

var doc = { hello: 'world'};

db.insert(doc, function (err, newDoc) {   
  alert(err); // err is null here as well. Doc will be in the memory storage but no persisted to file
});
like image 572
Bo Mil Avatar asked Oct 16 '25 03:10

Bo Mil


1 Answers

Although this question is pretty old, I'd like to share my experience for anyone facing a similar issue.

  1. NeDB API does not allow JSON input. You have to put in a javascript object. When you use JSON input, no error is returned and nothing will be persisted.
  2. 'null' is returned as error in callback to signal that no problem occurred. When saving the first JSON document it is indexed with 'undefined' key, because NeDB calls 'key = obj[fieldname[0]]' which returns 'undefined', when the obj is just a (JSON) string. No error is returned unfortunately. Inserting a second document will cause a unique constraint violation error in the callback as the key 'undefined' has already been taken. Anyhow, nothing will be persisted.

Try

var Datastore = require('nedb'), db = new Datastore({ filename: 'test.db' });

db.loadDatabase(function (error) {   
  if (error) {
      console.log('FATAL: local database could not be loaded. Caused by: ' + error);
      throw error;
    }
    console.log('INFO: local database loaded successfully.');
});

// creating the object with new, just to make it clear.
// var doc = {hello: 'world'}; should work too.
function myDoc(greeting)
{
   this.hello=greeting;
}
var doc = new myDoc('world');

db.insert(doc, function (error, newDoc) {   
  if (error) {
    console.log('ERROR: saving document: ' + JSON.stringify(doc) + '. Caused by: ' + error);
    throw error;
  }    
  console.log('INFO: successfully saved document: ' + JSON.stringify(newDoc));
});

Maybe it helps someone. :)

like image 138
flojupp Avatar answered Oct 18 '25 18:10

flojupp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!