-2

I am learning nedb and Node.js

Here is the database.js file:

// Initialize the database
var Datastore = require('nedb');
db = new Datastore({ filename: 'db/persons.db', autoload: true });

//Returns a specific Person
exports.getPerson = function(id){

  //Get the selected person details from the database
  db.findOne({ _id: id }, function(err, doc){

    console.log(doc);

    //Execute the parameter function
    return doc;

  });
}

Now in my main.js file I am calling the getPerson function as follows:

//Get person from the database
var person = database.getPerson(id);

console.log(id);
console.log(person);

document.getElementById('firstname').value = person.firstname;
document.getElementById('lastname').value = person.lastname;

In the output window of chrome browser:

enter image description here

Vishal
  • 6,238
  • 10
  • 82
  • 158

1 Answers1

2

I think you need to wrap your code into a callback.

(untested code)

//Returns a specific Person
exports.getPerson = function(id,callback){

   //Get the selected person details from the database
   db.findOne({ _id: id }, function(err, doc){

    console.log(doc);

    //Execute the parameter function
    callback(err,doc)

   });
}




var person = database.getPerson(id,function(err,person){

 console.log(id);
 console.log(person);

 document.getElementById('firstname').value = person.firstname;
 document.getElementById('lastname').value = person.lastname;
});
Ionel Lupu
  • 2,695
  • 6
  • 29
  • 53
  • Thank you. That works fine. It never came to my mind that I need to use callback function because I am using asyncronous behavior of node. – Vishal Feb 03 '17 at 07:52