How ensure default data in NeDB?

1.2k Views Asked by At

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)?

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

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)