node.js - NodeJS + MongoDB - simplifying functions -


i learning nodejs + mongodb. not want use mongoose of now. have below functions work fine. however, question how further this? both functions same except highlighted *** statement.

//for returning records  var resultsquery = function(search, select, callback) {     mongo.connect(mongourl, function(err, db) {         if (err){ throw err; }       ***  db.collection("coll").find(search, select).toarray(function(err, result) {             if (err) { throw err; }             callback(result);             db.close();         });     }); };  // updating records   var resultsupdate = function(filter, set, callback) {     mongo.connect(mongourl, function(err, db) {         if (err){ throw err; }        *** db.collection("coll").update(filter, set, function(err, result) {             if (err) { throw err; }             callback(result);             db.close();         });     }); }; 

put common things in 1 function , pass in callback:

var resultsquery = function(search, select, callback) {     xpto(callback, (db, cb) => db.collection("coll").find(search, select).toarray(cb)) };  // updating records  var resultsupdate = function(filter, set, callback) {     xpto(callback, (db, cb) =>  db.collection("coll").update(filter, set, cb)) };  function xpto(callback, op) {    mongo.connect(mongourl, function(err, db) {         if (err){ throw err; }           op(db, function(err, result) {             if (err) { throw err; }             callback(result);             db.close();         });     }); } 

there different ways this, think illustrates idea.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -