Search code examples
node.jsnedb

How to use nedb api from different modules in nodejs?


I have initialized a database in foo.js and saved some data into it.

var Datastore = require('nedb');
var bar = require('./bar.js');

var db = new Datastore({filename: './foo.db', autoload: true});
// saving some data here
db.insert(doc, function (err, newDoc) {}

Now I am trying to access the db in bar.js

var Datastore = require('nedb');

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

// finding data from same store
var bars = db.find({ system: 'solar' }, function (err, docs) {return docs}

Now I get this error: Uncaught Error: ENONET: no such file or directory, rename food.db -> foo.db~

I understand I can't call NeDB more than once for the same filename.

So how do I access the db and do operation on it on different module like above?


Solution

  • You can create file let's call it db.js with bellow code:

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

    now require this file wherever you want to use it

    var db = require('./db.js');
    
    db.insert(....);