I can insert and retrieve data from neDB database in nodejs. But I cannot pass data outside the function that retrieves it.
I read the neDB documentation and I searched and tried different combinations of callbacks and returns (see code below) without finding a solution.
I am new to javascript, so I donβt know if I donβt understand how to use variables at all, or is this problem related to using neDB specifically or both.
Can someone explain why the "x" in my code never contains JSON docs results from the database? How can I make it work?
var fs = require('fs'), Datastore = require('nedb') , db = new Datastore({ filename: 'datastore', autoload: true }); //generate data to add to datafile var document = { Shift: "Late" , StartTime: "4:00PM" , EndTime: "12:00AM" }; // add the generated data to datafile db.insert(document, function (err, newDoc) { }); //test to ensure that this search returns data db.find({ }, function (err, docs) { console.log(JSON.stringify(docs)); // logs all of the data in docs }); //attempt to get a variable "x" that has all //of the data from the datafile var x = function(err, callback){ db.find({ }, function (err, docs) { callback(docs); }); }; console.log(x); //logs "[Function]" var x = db.find({ }, function (err, docs) { return docs; }); console.log(x); //logs "undefined" var x = db.find({ }, function (err, docs) { }); console.log(x); //logs "undefined"*
source share