1

I'm trying to use NeDB as storage for my data in node-webkit application. I have the single collection named config.db:

var Datastore = require('nedb')
  , path = require('path')
  , db = new Datastore({ filename: path.join(require('nw.gui').App.dataPath, 'config.db') });

When user opens node-webkit application first time my config.db should have default data like:

{
   color: "red",
   font: 'bold'
   ...
}

Does NeDB have option for providing default data if there are no yet? Or What it the best way to save it if config.db is empty (in case if user opens node-webkit application first time)?

Erik
  • 14,060
  • 49
  • 132
  • 218

2 Answers2

1

As far as I know NeDB does not have an option to create initial data.

I think the easiest way to achieve this is to simply query whether there is data. If counting documents returns 0, obviously the initial data have not yet been saved, so you should do this now.

If you include this check in the startup code of your application, it will automatically initialize the data on first run, and afterwards simply do nothing.

Golo Roden
  • 140,679
  • 96
  • 298
  • 425
  • Thanks for the answer, I think It's a good trick. I'm just interested how another people workaround this? – Erik Nov 28 '14 at 19:07
  • For a more, well, "hardcore" version of the check you might as well verify whether NeDB's `.json` file has already been written to disk. If not, the database apparently is new ... anyway, I think the option to count documents is the better way. – Golo Roden Nov 28 '14 at 19:09
1

I came across this question while looking for a similar solution. I thought I'd share what I ended up with (this is a module):

var fs = require("fs");

module.exports = function (app) {
  var customizationService = app.service("customization");

  fs.readFile("./db/customization", "utf8", function (err, data) {
    if (err) {
      return console.log(err);
    }

    if (data) {
      // Sweet, carry on
    } else {
      var customOptions = {
        SiteTitle: "VendoMarket",
        SiteTagline: "The freshest eCommerce platform around"
      };

      // Save data to the locations service
      customizationService.create(customOptions);
    }
  });
};

And then in my app.js file:

//--------------------------------------
//  Initialize
//--------------------------------------

var vendoInit = require("./src/init");
vendoInit(app);

(My app.js file is at the base of my project, src is a folder next to it)

NetOperator Wibby
  • 1,354
  • 5
  • 22
  • 44