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
Post a Comment