I need to know how to execute Nodejs in a correct and orderly way:
Connect with Mongo. Execute query (Insert, Select, Update, Delete) Return results Close connection.
My idea is that whenever you need to make a query, call the connection, run the query and return the data and close it (so you would have the possibility to make many queries using a single connection). Following the manual of Mongodb I did the following but I do not know how to order myself:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/miConeccion';
function ConectarMongo(){
var promesa = new Promise(function(resolve, reject) {
MongoClient.connect(url, function(err, db) {
if(err){
reject(err);
return;
}
resolve(db)
});
});
return promesa;
}
var conexion = ConectarMongo();
conexion.then(
function(db){
return db;
},
function(err){
console.log("Hemos fallado en la conexión");
}
);