L
L
lex2016-10-04 16:08:41
JavaScript
lex, 2016-10-04 16:08:41

How to make such a helper?

Greetings!
Please tell me, maybe I’m suffering, of course, but I want to make myself a module with helpers for working with mongo, so that later I call the module and write a line and it’s off.
but I can’t understand how I can make it so that each method of the insertData type connects and disconnects itself, but also from the internal connect method and disconnects, well, all of a sudden, somewhere else this can be useful to me separately.
if I'm doing frank nonsense and everyone writes everything in its entirety if data is needed, let me know :))
thanks for your attention!

modules.define('dbcontrol', function(provide) {
  

  provide({

    _connect: function(task){
      var MongoClient = require('mongodb').MongoClient, assert = require('assert');
      var url = 'mongodb://localhost:27017/test';
      // Use connect method to connect to the server
      MongoClient.connect(url, function(err, db) {
        assert.equal(null, err);
        console.log("Connected successfully to mongoserver");
        task();
      });
    },
    _disconnect: function(db){
        db.close();
        console.log('Connection break');
    },
    insertData: function(data) {
      _this = this;
      _this.connect(task);
      // Get the documents collection
      var task = function () {

        var collection = db.collection('documents');
        // Insert some documents
        // console.log(sli[0]);
        collection.insert(data);
        _this.disconnect();
      
      }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
re67man, 2016-10-27
bem @bemdev

Depending on what you mean by helper. In my understanding, a helper is a module containing objects or functions that are wrappers over some objects or functions, which helps to reduce the amount of code in the module to which the helper is connected.
for example, if I understand you correctly.

где-то в коде.
var MONGO = {}

MONGO содержит
connect()
disconnect()
insertData()
isConnected()

function wrapInsertData(aData){
  if (!MONGO.isConnected()) {
    MONGO.connect(function(){
      MONGO.insert(aData)
      //делаете что то еще
    })
  }
}

In all projects I use such helpers. if there is an error somewhere in the wrapper, or you need to add some code, then there are no particular problems, and you won’t have to rewrite some of the modules by adding corrections.
No, **** you don't suffer from it.

_
_ _, 2016-10-05
@AMar4enko

Connect-disconnect for every sneeze? And if there are 100 requests in a cycle, for example?
Where are the promises/callbacks?
An application on a node is long-lived and can simultaneously execute several requests to the database, so a connection pool is created and requests are distributed among its elements.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question