I’m trying to user node-proxy to auto-magically read/write databases and I can’t figure a solution.
Here is the code:
var Proxy = typeof Proxy !== "undefined" ? Proxy : require("node-proxy");
var db = require('mongojs').connect('testdb',['colldb']);
function itemHandler(objid) {
var objid=objid;
return Proxy.create({
get: function(receiver, name) {
var name = name;
var hmmm;
//Problem Area!
db.colldb.findOne({"_id": db.ObjectId(objid)},function(err,doc){
hmmm = doc[name];
});
//Hmmm will obviously be undefined
return hmmm;
}
, set: function(receiver, name, val) {
// this can be async and I don't care :)
}
});
}
var test = itemHandler('4efc0c698b7e904ee982547f');
console.log(test.test);
process.exit(0);
Normally I would be ok with the call backs but I’m unsure how to make that work with node-proxy return on the ‘get’ method.
I’m looking for any solution to this that I can return the proxy data based on the database result.
Thanks
First, nothing is going to work in this example because of the
process.exit(0)line at the end. The program will terminate before the asynchronous functions complete.Second, you cannot return a value from the results of an asynchronous function. This is a fundamental concept. I am not familiar with
mongojs, but perhaps the following will work (I believe it would with Mongoose).Then the last lines would be something like:
Alternatively, you may be able to return a Promise/Future. Something like: