Answer the question
In order to leave comments, you need to log in
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
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)
//делаете что то еще
})
}
}
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 questionAsk a Question
731 491 924 answers to any question