node.js - Register callback and return document -
this first experience nodejs
and mongo. handling database query handlers in seperate js file, exported module in file, handles user requests. want search (findone) user document collection table, , return callee. cannot figure out how register callback , return document, once query execution completes..
here code, call method:
var record = mongodatahandler.getuserrequestobject(credentials.email, "");
how change call, such should like:
mongodatahandler.getuserrequestobject(credentials.email, "", function (result){ //handle result response here });
here getuserrequestobject, in js file (mongodatahandler.js):
var mongoclient = require('mongodb').mongoclient , format = require('util').format; var assert = require('assert'); var ds = require('../../server/datasources.json'); var dbmongoconnectorurl = ds.mongodbdev.url; module.exports = { getuserrequestobject : function(email, number){ var documentobj = null; mongoclient.connect(dbmongoconnectorurl, function(err, db) { if (err) throw err; console.log("connected database"); var cursor = db.collection('userrequestcode').find({"email": "someemail@gmail.com"}).sort( { _id: -1} ).limit(1); cursor.each(function(err,doc) { if (err) documentobj = {status:500, resp:err}; if (doc != null){ console.dir(doc); documentobj = {status:200, resp:doc}; return; } }); }); return documentobj; } }
the object returned (documentobj
) null. because not registered callback function.
how should register callback here, retrieved document collection works asynchronously?
just add argument function , treat function (there's no additional syntax, pretend it's function):
getuserrequestobject : function(email, number, my_own_callback){ /* .. lots of code .. */ // return documentobj; my_own_callback(documentobj); // how it's done }
Comments
Post a Comment