javascript - Node.js Connection mongodb using mongoclient -
In the node JS I just wanted to write some external method that gets the data from the mongode and returns it back to
In this I used the service.js Employee service works as a model, which interacts with the database and returns the data to service.js where our web services are written and this user responds to. employeeService .js Here I can get blank alarms by calling the asynchronous execution flow and service.js of the connector.connect method connected to my output console. Output [] in the output [] Mongo client This unusual flow is and MongoClient.js module to interact with the
mongodb . But the problem is that when the external method is called, this database returns the value before completing the connection method execution. Here I have to hold my Return Statement only till the
mongodb.connect method was completed. What to do? Here my code is,
var employee = requirement ('./ model / employeeService.js'); Var json = employee .getUser (employee ID);
export.getUser = function (employee ID) {var json = []; MongoClient.connect (db.getdbUrl), function (mistake, db) {if (err) {json = err;} else {document = (employeeId)? {_ Id: employeeId}: {}; Db.collection ('employee') .fid (document) .milit (50) .toArray (function (mistake, user) {if (mistake) {json = err;} else {console.log ("Inocide Mongo client") ; // This will execute another Json = Users;}}))}}}); Console.log ("outside", json); // it returns before json; }
not , such that
asynchronous code executes the code. If you want to return users back, then return it to
else {} ,
json = users;
Change by user; The end of your code. Learn more about
Asyncronus versus Synchronous calls and how to execute them. Also consider learning about
callback in javascript.
Comments
Post a Comment