I have a job class, defined in Javascript as such:
var Job = function() {};
module.exports = Job;
I then define a member function using its prototype. That works fine, until I try to use a value from a database to set the member variable:
// Create from an existing job ID
Job.prototype.createFromID = function( inID, callback ) {
// Start by making sure we're invalid
this.id = "";
// Connect to database
var db = MongoClient.connect('mongodb://localhost:27017/nodepurple', function( err, db ) {
if (err) { return false; }
// Find the job document we're interested in
db.collection('jobs').find({ jobID: inID }).limit( 1 ).toArray( function( err, theJobs ) {
if (theJobs.length == 1) {
this.id = theJobs[0].jobID;
// Close the database
db.close();
callback( (this.id != ""), this );
}
}); // Find
}); // Connect
}
The purpose of this function is to:
- Get a MongoDB document defining the specific job I'm interested in (defined by the "inID" parameter.
- Fill a bunch of member variables of the job instance for which this function was called.
This doesn't work. I think I understand why it doesn't work, when these MongoDB callbacks return, I'm assuming I'm no longer in the right context to make this work, but I'm struggling to see how this can be resolved.
So, how can I take the value MongoDB gives me back for jobID and use that to populate the "id" member variable in the particular Job instance I'm working on?