简体   繁体   中英

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?

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(....);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM